Iterator and Enumeration - Differences Explained
In this article, I will be comparing the Iterator and Enumeration interfaces. I will be explaining the similarities and differences between Iterator and Enumeration. Definitions Both Iterator and Enumeration are interfaces defined in the Java Collection framework. You can use both to loop through the elements of a Collection. Let us first understand how they work Iterator Iterator is an interface defined in the Java Collection framework. You can use it to loop through the elements of a collection. The following code demonstrates this: List<Integer> numbers = Arrays.asList(2,4,6,8,10); Iterator<Integer> itr = numbers.iterator(); while (itr.hasNext()) { System.out.print(itr.next()+" "); } This code uses an Iterator to loop through the elements in a List and print them. Iterator.hasNext() method returns true if there are more elements in the collection. The iterator.next() method returns the next element in the collection. So this code prints the following ou