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.
Hi, I am David the creator of https://www.springmockexams.com and https://www.javamockexams.com.
ReplyDeleteI really want to thank you for this post, I am going to share it on all my social media, if you do not mind!
I am also really enthusiast to announce some very exciting news: to celebrate the imminent release of Spring 5 and Java 9 we launched our simulators SALE CAMPAIGN. We lowered the price of our simulators at www.springmockexams.com and www.javamockexams.com for limited time only.
If the audience is interested in accessing OUR PRICE OFFER, they can take a look here http://www.cm.gy/sme and here http://www.clktr4ck.com/java
Thanks and check your featuring on our social medias!
David