Iterator Interface in Java

Advertisements

Prev Tutorial Next Tutorial

Iterator Interface in Java

It is one of the predefined interface present in java.util.* package. The purpose of this interface is that to extract or retrieve the elements of collection variable only in forward direction but not in backward direction. By default an object of iterator is pointing just before the first element of any collection framework variable.

Points to Remember

  • Iterator allows to remove the elements from collection object.
  • Iterator is not Synchronized.
  • Using Iterator elements of collection can be access only in forward direction.
  • Iterator can be available to all the collection classes.
  • Every collection class contains Iterator() and that returns Iterator object, using this object reference elements can be retrieved from collection.

Methods of Iterator Interface

  • public boolean hasNext()
  • public object next()
  • remove()

public boolean hasNext()

This method return true provided by Iterator interface object is having next element otherwise it returns false.

public object next()

This method is used for retrieving next element of any collection framework variable provided public boolean hasNext(). If next elements are available then this method returns true other wise it return false.

public object remove()

Remove from collection the last element returned by Iterator.

Example of Iterator

import java.util.*;

class IteratorDemo
{
public static void main(String args[])
{  

ArrayList<Integer> al=new ArrayList<Integer>();  // creating arraylist
al.add(10);
al.add(20);
al.add(30);

Iterator itr=al.iterator();  // getting Iterator from arraylist to traverse elements  
while(itr.hasNext())
{  
System.out.println(itr.next());  
  }  
 }  
}  

Output

10
20
30

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements