I get an Iterator back from a class and I would like to get the xth element of that iterator. I know I could load it into an ArrayList in a loop or check a counter, but that seems inefficient/ugly. What is the best way to do this?
I thought something like,
List al = new ArrayList(myIterator);
myval = al.get(6);
But that constructor is undefined. thanks.
Nope, you've named the only approaches. You're going to end up needing a for
loop to iterate to the appropriate position.
A few utility libraries have shortcuts to load an Iterator
's contents into an ArrayList
, or to get the n
th element of an Iterator
, but there's nothing built into the JDK.