Java Iterator iterates only once!


In Java, If you use Iterator object to traverse through Lists or Arraylists, then remember that an iterator runs through a list only once.

Example

Iterator<String> x = someStringList.iterator();

Iterator<String> y = someOtherStringList.iterator();

while(x.hasNext())

{

While(y.hasNext())

{

//do something

y.next()

}

}

The y.hasnext loop wont loop thru y’s dataset for every iteration of x, because it has reached the end of the iteration the very first time the first while loop gets executed. So solution is

Iterator<String> x = someStringList.iterator();

while(x.hasNext())

{

Iterator<String> y = someOtherStringList.iterator();

While(y.hasNext())

{

//do something

y.next()

}

}

Advertisements

About vatsalad

Hi, I'm Vatsala
This entry was posted in java and tagged , , . Bookmark the permalink.