Hi all,
I would like to know what is the difference between these 2.
ArrayList list = new ArrayList
for(int i=0; i<list.size(); i++){
//do stuff
}
Iterator i = list.iterator();
while(i.hasNext(){
do stuff
}
Is there performance issues?
One important difference is the fact that the collection may not be
modified inside the scope of an iterator (it will throw
ConcurrentModificationException).
You are only referring to ArrayList so some of the generality that's in
the Collections and List Iterator are presumably of no concern, and you
want to know if looping through an array with an integer index counter
is higher performance than using the Iterator.
That's a very good question. The Iterator is not implemented as an
indexed loop, at least not in Sun Java. The collection always has a
getter armed with the iterator's next value. Much of the collection's
internal implementation is done via the iterator. But the pieces of
ArrayList that are optimized for speed, skip bounds checking and use int
array offsets to do their work.
For comparing performance, I think you have to consider the runtime
behavior of things that are private to a class (because of inlining)
differently from things you do outside that class.
Maybe someone can get Bloch to answer this question directly. He would
know.