remove( ) method of Iterator interface in java.

remove( ) method of Iterator interface in java.


Posted in : Core Java Posted on : January 24, 2011 at 4:53 PM Comments : [ 0 ]

In the following example we will show you how can you delete an element from collection using remove( ) method of Iterator interface in java.

remove( ) method of Iterator interface in java.

In the following example we will show you how can you delete an element from collection using remove( ) method of Iterator interface in java.

Syntax

public void remove( )

This method do not returns any value.

In this method you can delete the last called element from the underlying collection which is gave back by the iterator. It is an optional operation.

Parameter Description 

This method does not take any argument.

Example of remove( ) method 

In this example we will show you how does remove( ) method work in a collection using Iterator interface. This example will help you to understand how can you delete the last element returned by the iterator from a collection. Through this example we will show you how iterator( ) method is used and how the remove( ) method is used after calling the next( ) method for deleting the element from collection using Iterator object.

Example:-

package Devmanuals.com;
import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorRemove {
  public static void main(String[] args) {
    ArrayList<Integer> al = new ArrayList<Integer>();
    for (int i = 10; i <= 20; i++)
      al.add(i);
    Iterator<Integer> itr = al.iterator();
    System.out.println("Is list contain more elements ? " + itr.hasNext());
    System.out.println("Old list = " + al);
    while (itr.hasNext()) {
      Integer i1 = (Integeritr.next();
      if (i1 == 15)
        itr.remove();
    }
    System.out.println("After removing the last called ");
    System.out.println("element by iterator, then list =  " + al);
  }
}

Output :

Is list contain more elements ? true
Old list = [1011121314151617181920]
After removing the last called 
element by iterator, then list =  [10111213141617181920]

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics