Iterator in Java is nothing but a traversing object, made specifically for Collection objects like List and Set. we have already aware about different kind of traversing methods like for-loop ,while loop,do-while,for each lop etc,they all are index based traversing but as we know Java is purely object oriented language there is always possible ways of doing things using objects so Iterator is a way to traverse as well as access the data from the collection. Even with traversing with object we have Enumeration, Iterator and ListIterator in Java which we will in this Java Iterator tutorial.
What is Iterator in Java API:
Java iterator is an interface belongs to collection framework allow us to traverse the collection and access the data element of collection without bothering the user about specific implementation of that collection it. Basically List and set collection provides the iterator. You can get Iterator from ArrayList, LinkedList, and TreeSet etc. Map implementation such as HashMap doesn’t provide Iterator directory but you can get there keySet or Value Set and can iterator through that collection.
Syntax:
It comes inside java.util package. as public interface Iterator and
boolean hasNext(): this method returns true if this Iterator has more element to iterate.
Object next(): return the next element in the collection until the hasNext() method return true. Its always recommended to call hasNext() method before calling next() method to avoid java.util.NoSuchElementException: Hashtable Iterator
remove(): method remove the last element return by the iterator this method only calls once per call to next().
How to create Iterator in Java:
Every collection classes provides an iterator() method that returns an iterator to the beginning of the collection. By using this iterator object, we can access each element in the collection, one element at a time. In general, to use an iterator to traverse through the contents of a collection follow these steps:
1. First obtain an iterator to the beginning of the collection by calling the collection's iterator( )
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
Java Iterator tutorial and Example
Example of How to use Iterator in Java
Here is complete code example of How to use Iterator in Java. This Java program creates Hashtable, populate it with dummy data and than uses Iterator to traverse Map and prints key and value for each Entry. This Java Program uses Generic version of Iterator to ensure type-safety and avoid casting .
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/**
* Simple Java Program which shows How to use Iterator in Java to loop through all elements
* of Collection classes like ArrayList, LinkedList, HashSet or Map implementation like
* HashMap,TreeMap and Hashtable.
*/
public class IteratorExample{
public static void main(String[] args) {
//Hashtable instance used for Iterator Example in Java
Hashtable<Integer, String> stockTable=new Hashtable<Integer,String>();
//Populating Hashtable instance with sample values
stockTable.put(new Integer(1), "Two");
stockTable.put(new Integer(2), "One");
stockTable.put(new Integer(4), "Four");
stockTable.put(new Integer(3), "Three");
//Getting Set of keys for Iteration
Set<Entry<Integer, String>> stockSet = stockTable.entrySet();
// Using Iterator to loop Map in Java, here Map implementation is Hashtable
Iterator<Entry<Integer, String>> i= stockSet.iterator();
System.out.println("Iterating over Hashtable in Java");
//Iterator begins
while(i.hasNext()){
Map.Entry<Integer,String> m=i.next();
int key = m.getKey();
String value=m.getValue();
System.out.println("Key :"+key+" value :"+value);
}
System.out.println("Iteration over Hashtable finished");
}
}
Output:
Iterating over Hashtable in Java
Key :4 value :Four
Key :3 value :Three
Key :2 value :One
Key :1 value :Two
Iteration over Hashtable finished
Why use Iterator when we have Enumerator:
Both Iterator and Enumerator is used for traversing of collection but Iterator is more enhanced in terms of extra method remove () it provide us for modify the collection which is not available in enumeration along with that it is more secure it doesn’t allow another thread to modify the collection when some another thread is iterating the collection and throws concurrentModificationException. Along with this method name are also very convenient in Iterator which is not major difference but make use of iterator more easy.
What is List Iterator in Java?
ListIterator in Java is an Iterator which allows user to traverse Collection like ArrayList and HashSet in both direction by using method previous() and next (). You can obtain ListIterator from all List implementation including ArrayList and LinkedList. ListIterator doesn’t keep current index and its current position is determined by call to next() or previous() based on direction of traversing.
Important point about Iterator in Java:
1) Iterator in Java support generics so always use Generic version of Iterator rather than using Iterator with raw type.
2) If you want to remove objects from Collection than don't use for-each loop instead use Iterator's remove() method to avoid any ConcurrentModificationException.
3) Iterating over collection using Iterator is subject to ConcurrentModificationException if Collection is modified after Iteration started, but this only happens in case of fail-fast Iterators.
4) There are two types of Iterators in Java, fail-fast and fail-safe, check difference between fail-safe and fail-fast Iterator for more details.
5) List collection type also supports ListIterator which has add() method to add elements in collection while Iterating. There are some more differences between Iterator and ListIterator like bidirectional traversing, which we have discussed above. Also why ListIterator has add() method is a popular Java Collection Interview question.
Some of my older Java Program tutorial you may find interesting
Tidak ada komentar:
Posting Komentar