Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Beginning Java and the fly likes Why doesn't this iterator return an object? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Why doesn Watch "Why doesn New topic
Author

Why doesn't this iterator return an object?

James Gibbs
Greenhorn

Joined: Feb 21, 2013
Posts: 29

I'm trying to iterate through a list and add all matching nodes to another list. However in the specific line affiliateResults.add(iterator.next()), iterator.next doesn't return an object, as when I later inspect affiliateResults it is empty. Any ideas where I'm going wrong?

Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41109
    
  45
You're potentially calling iterator.next() twice for each call to iterator.hasNext() (in lines 3 and 8) - you should call next() only once for each call to hasNext().


Ping & DNS - my free Android networking tools app
James Gibbs
Greenhorn

Joined: Feb 21, 2013
Posts: 29

ah thanks I see what you mean. Now it changes my question how I convert a JsonNode to a Row? maybe I'd be better off with a for loop
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 41109
    
  45
Instead of line 5, write something like:

Row row = iterator.next();

JsonNode doc = row.getValueAsNode();
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4343
    
    8

James Gibbs wrote:ah thanks I see what you mean. Now it changes my question how I convert a JsonNode to a Row? maybe I'd be better off with a for loop

I'm probably misunderstanding what you're trying to do here...but iterator.next() is returning a Row. If you want a Row instead of a JsonNode, don't call getValueAsNode() on it.


By the way, there's a little trick you can use instead of this pattern:

You can replace that with:
but even more concise is:
James Gibbs
Greenhorn

Joined: Feb 21, 2013
Posts: 29

Thanks Ulf and Matt, with your help I saw the errors of my ways and got it working.

Matt, thank you so much for your advice about the inner if conditional, when I was writing it I was thinking "there has to be better way", did consider && but had completely forgotten that it short circuits so thought if I used it it might blow up if x.equals("yes") was run before the null check.
 
Don't get me started about those stupid light bulbs.
 
subject: Why doesn't this iterator return an object?
 
Similar Threads
Object Equality Google gwava and Apache Commons
Strings in a List
doubt with for-each loop
Iterator
How to create Java 3D Array Object ?