We can use for loop, advanced for loop or iterator for iterating over Collection.
But using iterator over other competitors gives some advantages like:
NOTE: Try to remove object from Collection using for loop and see if you can or not.
But using iterator over other competitors gives some advantages like:
- By using for loop you cannot update(add/remove) the Collection whereas with iterator we can easily update Collection.
Example for updating list by iterator:
package
javaRadarArrayList;
import
java.util.ArrayList;
import
java.util.Iterator;
public class UpdateList {
public static void main(String[] args) {
//create Array
List
ArrayList<String>
javaRadarList = new
ArrayList<String>();
//Add elements
to ArrayList
javaRadarList.add("Java");
javaRadarList.add("Spring");
javaRadarList.add("Hibernate");
javaRadarList.add("EJB");
System.out.println("Original
list:" +javaRadarList);
Iterator<String>
itr = javaRadarList.iterator();
while(itr.hasNext()){
String
token = itr.next();
itr.remove();
System.out.println("list
afer modification:" +javaRadarList);
}
}
}
OUTPUT:
Original list:[Java, Spring,
Hibernate, EJB]
list afer modification:[Spring,
Hibernate, EJB]
list afer
modification:[Hibernate, EJB]
list afer modification:[EJB]
list afer modification:[]
- In situations where there is no idea of what type of Collection will be used we can use iterator to traverse over the collection as all Collection implements iterator interface.