I was browsing over the following code example:
public class GenericTest {
public static void main (String[] args) {
ArrayList<String> myList = new ArrayList<String>();
String s1 = "one";
String s2 = "two";
String s3 = "three";
myList.add(s1); myList.add(s2); myList.add(s3);
Iterator<String> itr = myList.iterator();
String st;
while (itr.hasNext()) {
st = itr.next();
System.out.println(st);
}
}
}
I'm wondering what are the benefits of using an implementation of the Iterator
interface instead of using a plain-old for-each loop?
for (String str : myList) {
System.out.println(str);
}
If this example is not relevant, what would be a good situation when we should use the Iterator?
By using Iterator, we can perform both read and remove operations. Iterator must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface.
Iterator and for-each loop are faster than simple for loop for collections with no random access, while in collections which allows random access there is no performance change with for-each loop/for loop/iterator.
The Iterator interface of the Java collections framework allows us to access elements of a collection. It has a subinterface ListIterator . All the Java collections include an iterator() method. This method returns an instance of iterator used to iterate over elements of collections.
Basically, foreach loop is a shortcut for the most common use of an iterator. This is, iterate through all elements. But there are some differences:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With