This is one of the good interview questions.
In this post, I am going to explain some difference between iterator and
enumerator, how to create custom iterator etc.,
One important difference is, Enumeration
is introduced in Jdk 1.0, all the legacy classes like HashTable, Vector,
StringTokenizer implements Enumeration interface. Where as Iterator interface
is introduced in Jdk 1.2, it provides all the functionality provided by
Enumeration, in addition to this, by using iterator you can remove an element
while traversing.
Enumeration interface provide following
methods.
Method
|
Description
|
boolean hasMoreElements()
|
Return true if this enumeration object
contains at least one more element to provide; false otherwise.
|
E nextElement()
|
Return next element of this
enumeration
|
Example
import java.util.Enumeration; import java.util.Vector; public class EnumerationDemo { public static void main(String args[]) { Vector<Integer> vector = new Vector<>(); vector.add(100); vector.add(35); vector.add(54); vector.add(321); vector.add(432); vector.add(5); Enumeration<Integer> enumerator = vector.elements(); while (enumerator.hasMoreElements()) { System.out.println(enumerator.nextElement()); } } }
Output
100 35 54 321 432 5
Iterator
interface provides following methods.
Method
|
Description
|
boolean
hasNext()
|
Return true, if the iterator has more
elements.
|
E next()
|
Return the next element in the
iteration.
|
default void
remove()
|
Remove the last element returned by
this iterator.
|
default
void forEachRemaining(Consumer<? super E> action)
|
Performs the given action for each
remaining element until all elements have been processed or the action throws
an exception.
|
import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class IteratorDemo { public static void main(String args[]) { List<Integer> primes = new LinkedList<>(); primes.add(2); primes.add(3); primes.add(5); primes.add(7); primes.add(11); Iterator<Integer> iter = primes.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }
Output
2 3 5 7 11
Implementing Custom Iterator
import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; public class CustomList<E> { private List<E> tempList = new ArrayList<>(); private int size = -1; public void add(E ele) { size++; tempList.add(ele); } public Iterator<E> iterator() { return new Itr(); } private class Itr implements Iterator<E> { private int cursor = -1; @Override public boolean hasNext() { return cursor < size; } @Override public E next() { if (cursor >= size) { throw new NoSuchElementException(); } cursor++; return tempList.get(cursor); } } }
Output
10 20 30 40 50 60
You may like
No comments:
Post a Comment