Iterator
It has three methods:
- hasNext()
- next()
- remove()
import java.util.Iterator; import java.util.ArrayList; public class NewTechIteratorExample { public static void main(String[] args) { ArrayList arrList = new ArrayList(); arrList.add("1"); arrList.add("2"); arrList.add("3"); arrList.add("4"); arrList.add("5"); System.out.println("ArrayList before removal of element: "); for(int index = 0; index < arrList.size(); index++) { System.out.println(arrList.get(index)); } Iterator itr = arrList.iterator(); while(itr.hasNext()){ String str = (String)itr.next(); if(str.equals("2")) { itr.remove(); break; } } System.out.println("ArrayList after removal of element : "); for(int index = 0; index < arrList.size(); index++) { System.out.println(arrList.get(index)); } } } This would produce the following result: ArrayList before removal of element : 1 2 3 4 5 ArrayList after removal of element : 1 3 4 5
Enumeration
It has following methods:
- hasMoreElements()
- nextElement()
import java.util.Vector; import java.util.Enumeration; public class NewTechEnumerationTest { public static void main(String args[]) { Enumeration days; Vector dayNames = new Vector(); dayNames.add("Sunday"); dayNames.add("Monday"); dayNames.add("Tuesday"); dayNames.add("Wednesday"); dayNames.add("Thursday"); dayNames.add("Friday"); dayNames.add("Saturday"); days = dayNames.elements(); while (days.hasMoreElements()){ System.out.println(days.nextElement()); } } } This would produce the following result: Sunday Monday Tuesday Wednesday Thursday Friday Saturday
- Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has methods only to traverse the collection objects, whereas Iterator can manipulate the collection objects like removing the objects from collection e.g. Arraylist.
- Iterators are more secure and safe as compared to Enumeration because it does not allow a thread to modify the collection object while some other thread is iterating over it. If a thread tries to modify the collection while some other thread is traversing then iterator fails quickly by throwing ConcurrentModificationException.
I hope this article helped you to understand. Please feel free to post any comment or question if you have any problem and find difficulty in understanding the article.
0 comments