InterviewSolution
| 1. |
When to use the Iterator and Enumeration? What is the possible use case? |
|
Answer» Iterator and Enumerator are two different classes in the collection api, which is used to perform the traversing to a collection object. The use case is whenever there is a NEED to traverse the elements and there is no need to add and update the elements in the list than its good to go with the Enumerator, an enumerator is basically a legacy class which is a SUPPORT to all the legacy classes Vector, Stack, HashTable. Whereas Iterator is an advanced way to handle the traversing when there is a requirement to modify the elements in the collection object than we can use the Iterator. Iterator can support all kinds of Collection class like List, Map and Set. Iterator can provide fail-safe and fall fast according to the corresponding collection class. Below is the code snippet for Enumeration import java.util.*; public class EnumerationIteration { public static void MAIN(String args[]) { Vector Barista = new Vector(); Barista.add("Chipotele"); Barista.add("Starbucks"); Barista.add("Dunkin Donuts"); // Creating the enumeration from Vector Enumeration enumerate = Barista.elements(); // Traversing to the elements using hasMoreElements() method. while(enumerate.hasMoreElements()) { // System.out.println(enumerate.nextElement()); } } } // Below is the code snippet for Iterator import java.util.*; public class EnumerationIteration { public static void main(String args[]) { Vector foodChain = new Vector(); foodChain.add("Mc Donalds"); foodChain.add("Subway"); foodChain.add("Chipotele"); System.out.println("USA Food SHOPS:"); Iterator it = foodChain.iterator(); while(it.hasNext()) { System.out.println(it.next()); } } } |
|