ListIterator interface in java

ListIterator:

ListIterator interface is used to traverse the elements in both forward and backward directions.
Note: Can traverse elements in both forward and backward directions.

Commonly Used methods of ListIterator Interface:

1. hasNext(): Returns true if iterator has more elements in forward direction otherwise returns false.

Syntax: public boolean hasNext().

2. next(): Returns the element and point to the next element.

Syntax: public object next().

3. hasPrevious(): Returns true if iterator has more elements in back direction otherwise returns false.

Syntax: public boolean hasPrevious().

4. previous(): Returns the element and point to the previous element.

Syntax: public object ne previous().

ListIterator interface example:

ListIteratorTest.java

import java.util.ArrayList;
import java.util.ListIterator;
 
/**
 * This class is used to show the ListIterator functionality.
 * @author w3spoint
 */
public class ListIteratorTest {
	public static void main(String args[]){
		//Create ArrayList object.
		ArrayList arrayList = new ArrayList();
 
		//Add objects to the HashSet.
		arrayList.add("Amani");
		arrayList.add("Prabhjot");
		arrayList.add("Nidhi");
		arrayList.add("Vandana");
		arrayList.add("Poonam");
 
		//Get the ListIterator object.
		ListIterator listIterator=arrayList.listIterator();
 
		//Print the ArrayList elements in forward direction.
        	System.out.println("ArrayList elements in " + 
                                          "forward direction:");
		while(listIterator.hasNext()){  
		   System.out.println(listIterator.next());  
		} 
 
		//Print the ArrayList elements in backward direction.
		System.out.println("ArrayList elements in " +
				"backward direction:");
		while(listIterator.hasPrevious()){  
		   System.out.println(listIterator.previous());  
		} 
	}
}

Output:

ArrayList elements in forward direction:
Amani
Prabhjot
Nidhi
Vandana
Poonam
ArrayList elements in backward direction:
Poonam
Vandana
Nidhi
Prabhjot
Amani

Download this example.

 
Next Topic: Servlet Tutorial with example.
Previous Topic: Hashtable in java with example.

Content Protection by DMCA.com
Please Share