Friday, 6 November 2015

Difference between Enumeration and Iterator ?


Both Iterator and Enumeration allows you to traverse over elements of Collections in Java.Iterator allows you to remove elements from collection during traversal but Enumeration doesn't allow that. Enumeration is introduced in legacy class and not all Collection class supports it .For example:- Vector supports Enumeration but ArrayList doesn't.


Example of Iterator:-

 public static void main(String[] args) {  
           List<String> list = new ArrayList<String>();  
           list.add("Java");  
           list.add("C++");  
           list.add("C");  
           list.add("Python");  
           Iterator<String> itr = list.iterator();  
           while (itr.hasNext()) {  
                System.out.println(itr.next());  
           }  

Example of Enumeration:-


 public static void main(String[] args) {  
           List<String> list = new ArrayList<String>();  
           list.add("Java");  
           list.add("C++");  
           list.add("C");  
           list.add("Python");  
           Enumeration<String> e=Collections.enumeration(list);  
           while(e.hasMoreElements())  
           {  
                System.out.println(e.nextElement());  
           }  
      }  




Enumeration
Iterator
Enumeration doesn't have a remove() method
Iterator has a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects
Can be abstract, final, native, static, or synchronized


Note:- Enumeration is used whenever we want to make Collection objects as Read-only.


Enjoy Reading

No comments:

Post a Comment