Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Iterator in Java

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 190
    Comment on it

    Iterator in Java

    java.util package has public interface Iterator. Iterator can be defined as interface which belongs to collection framework. Iterator as name suggest allows accessing,removing and traversing data element contained in a collection. It contains three methods: 

    1. boolean hasNext(): If Iterator has more element to iterate then true is returned.

    2. Object next(): The next element in the collection is returned until the hasNext()method return true. This method throws ‘NoSuchElementException’ if there is no next element.

    3.void remove(): This method removes current element from the collection. An ‘IllegalStateException’ is thrown if this function is called before next( ) is invoked.

    Example of Iterator in java:

    // Java code to illustrate the use of iterator
    import java.io.*;
    import java.util.*;
    
    class Test
    {
    	public static void main (String[] args)
    	{
    		ArrayList<String> list = new ArrayList<String>();
    
    		list.add("A");
    		list.add("B");
    		list.add("C");
    		list.add("D");
    		list.add("E");
    
    		// Iterator to traverse the list
    		Iterator iterator = list.iterator();
    
    		System.out.println("List elements : ");
    
    		while (iterator.hasNext())
    		{
    		    String i1 = (String) iterator.next();
    		    if(i1=="A")
    		    iterator.remove();
    		    else
    			System.out.print(i1+ " ");
    		
    		}	
    		System.out.println();
    	}
    }
    

    Output:

    List elements : 
    B C D E 

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: