Consider the following scenario.
List<String> list = new ArrayList<>();
Now I added the String
values for this list.
I used following ways to go each and every element in the list.
Option one- use for-each
for (String i : list) { System.out.println(i); }
Option two- use Iterator
Iterator it=list.iterator(); while (it.hasNext()){ System.out.println(it.next()); }
I just want to know is there any performance advantage if I use for-each
instead of Iterator
. And also is it a bad practice to use Iterator now a days in Java?
Difference between the two traversalsIn for-each loop, we can't modify collection, it will throw a ConcurrentModificationException on the other hand with iterator we can modify collection. Modifying a collection simply means removing an element or changing content of an item stored in the collection.
An iterator provides a number of operations for traversing and accessing data. An iterator may wrap any datastructure like array. An iterator may be thread safe while a for loop alone cannot be as it is accessing elements directly.
Java Programming for Complete Stranger Collections can be iterated easily using two approaches. Using for-Each loop − Use a foreach loop and access the array using object. Using Iterator − Use a foreach loop and access the array using object.
Deductions. This foreach loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array. The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
for-each
is syntactic sugar for using iterators
(approach 2).
You might need to use iterators
if you need to modify collection in your loop. First approach will throw exception.
for (String i : list) { System.out.println(i); list.remove(i); // throws exception } Iterator it=list.iterator(); while (it.hasNext()){ System.out.println(it.next()); it.remove(); // valid here }
The difference is largely syntactic sugar except that an Iterator can remove items from the Collection it is iterating. Technically, enhanced for loops allow you to loop over anything that's Iterable, which at a minimum includes both Collections and arrays.
Don't worry about performance differences. Such micro-optimization is an irrelevant distraction. If you need to remove items as you go, use an Iterator. Otherwise for loops tend to be used more just because they're more readable ie:
for (String s : stringList) { ... }
vs:
for (Iterator<String> iter = stringList.iterator(); iter.hasNext(); ) { String s = iter.next(); ... }
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