All About Iterator Interface in Collection in Java

Iterator Interface in Java
Iterator Interface in Java

Iterator Interface in Java:

The Iterator interface(added in java-2) has the same effect and style as the Enumerated interface.It enables us to sequentially traverse and access the elements contained in a collection.The elements of a collection can be accessed using the method defined by Iterator interface.It proves easy methods like add() and remove() to add and remove items.

The vector,Hashtable and Hashmap classes all have an iterator method which returns an iterator of their contents.

The Iterator interface has the following methods:


hasNext();//Returns true if the collection contains more than one element
next();//returns the next element from the collection.
remove();//removes the current element from the collection.
next() method returns the next element if it is available in the collection else it will throw the NoSuchElementException.
remove() method throws the IllegalStateException when there is no element in the collection.
Using the iterator interface we can insert elements only at the end of the list.If we need to insert element at any required location of the list,we need to use ListIterator Interface.(It extends Iterator interface).
The ListIterator has a special method called add(int index,Object obj). This nethod add an object at the specified location or index.

An example:


Vector v=new vector();
v.add("Apple");
v.add("Banana");
v.add("Pear");
v.add("Grape");
Iterator itr=v.iterator();
while(itr.hasMore()){
String s=(String)itr.next();
System.out.println(s);
}
 
All About Iterator Interface in Collection in Java All About Iterator Interface in Collection in Java Reviewed by Animesh Chatterjee on December 20, 2018 Rating: 5

No comments:

Powered by Blogger.