Java Iterator is used to iterate over Collections in Java. By Iteration,
I mean, going over each element stored in collection and optionally performing
some operation e.g. printing value of element, updating object or removing
object from Collection. Iterator
was not part of first Java release, and a similar class Enumeration was there
to provide Iteration functionality. Iterator in Java was introduced form JDK
1.4 and it provides alternative to Enumeration, which is obsolete now days.
Iterator is different to Enumeration in two main ways, first, Iterator allows
programmer to remove elements from Collection during iteration. Second, names
are shortened and improved in Iterator, by the way, you can see difference
between Iterator and Enumeration for more differences. It's one of the
frequently asked Java
Interview question. Iterator is an interface and enhanced to support
Generic from Java 1.5 release. Almost all popular collection implements
Iterator, including ArrayList, LinkedList and HashSet. hasNext() method of
Iterator is used as condition while Iterating, and next() method
actually returns object, next in sequence maintained by Collection itself. In this
Java programming tutorial, we will learn How to use Iterator in Java by coding
Iterator example and iterating over ArrayList.
How to use Iterator in Java - Example
Using Iterator is probably simplest thing you will learn in Java
programming. Every Collection, which implements Iterator interface,
provides iterator() method which returns Iterator
instance. This method comes from java.util.Iterator interface
and return a type-safe
Iterator. Now, In order to start iterating or navigating, we can use while loop
and hasNext() method to check whether, there is more elements in
Iterator or not. In each run of while loop, we get access to one element from Java
Collection. In this example, we first print value of element and
subsequently remove it from Collection. So, at the end of our iteration, Java collection
should be empty. By the way, It's also worth knowing that there are two kinds
of Iterator in Java, fail-safe and fail-fast. fail-safe
Iterator doesn't throw ConcurrentModificationException during
iteration while fail-fast does, if, Iterator realizes any structural change in
Collection once Iteration begins. See difference
between fail-fast and fail-safe Iterator, to know more about it.Java Iterator Example
Without, delaying any more, here is our Java program to show, How to use Iterator in Java.
/** * Java program to show, How to use Iterator in Java. * Iterator provides a convenient way to access every element from Java Collections. * Iterator is also handy in removing elements from Collection. * @author java67 */ public class IteratorHowTo { public static void main(String args[]) { //This is nice way to create List, but it's fixed lenght, don't supprot remove() List<String> androidVersions = Arrays.asList("Petit Four", "Cupcake", "Donut", "Eclair", "Froyo","Gingerbread", "Honeycomb", "Ice Cream Sandwich", "Jelly Bean"); //this is bettern than adding individual elements - No? List<String> android = new ArrayList<String>(androidVersions); //Getting Iterator from List Iterator<String> iterator = android.iterator(); System.out.println("Size of List before Iteratation " + android.size()); //Using Iterator to iterate over List, acces object one by one while(iterator.hasNext()){ String version = iterator.next(); System.out.println(version); /* android.remove(version); */ //removing object from List - ConcurrentModificationException iterator.remove(); // you should be using Iterator's remove method } System.out.println("Size of list after removing object during Iteration : " + android.size()); } } Output: Size of List before Iteratation 9 Petit Four Cupcake Donut Eclair Froyo Gingerbread Honeycomb Ice Cream Sandwich Jelly Bean Size of list after removing object during Iteration : 0
There are couple of interesting thing to note in this code. First thing
is nice
way of creating List in one line, This is best way to create List, if you
know values in advance. Unfortunately, that List is fixed length List and doesn't
support remove operation, calling remove() will
result in "Exception in thread "main"
java.lang.UnsupportedOperationException". By the way, it's important
to remember that this is not a read
only Collection, you can still modify existing elements by using set(index) method.
Second interesting thing is using copy constructor of Collection, which is a
nice way to copy
elements from one Collection to another. Now last and probably most
important thing to note is using iterator.remove() method to
remove objects from List. Many programmer make mistake by calling List.remove() method
instead of Iterator.remove() here, earlier will throw ConcurrentModificationException. You should
only use remove() method from java.util.Iterator to remove
elements from collection, while iterating.
That's
all about Iterator in Java. Though we have seen a relative simple
example of Java Iterator, it does demonstrate most common usage of
Iterator. Just
beware of ConcurrentModificationExcepton, while
iterating over Java Collections in multi-threading environment. Though, most of
Concurrent
Collections such as ConcurrentHashMap and CopyOnWriteArrayList supports fail-safe Iterator, more popular ones like ArrayList or HashSet
iterators are still fail-fast.
Related Java Programming Tutorials from Java67

Thank you so much for your post. So interesting details about iterators.
ReplyDelete