previousIndex( ) method of ListIterator Interface in java.

previousIndex( ) method of ListIterator Interface in java.


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

In this method, you can find the position of an element into a list in backward direction. It gives the position value of an element which is just situated before the

previousIndex( ) method of ListIterator Interface in java.

In the following example we will show you how can previousIndex( ) method is implemented in ListIterator interface.

Syntax

public int previousIndex( )

This method gives the position of an element that would be backed by a later call to previous( ).

In this method, you can find the position of an element into a list in backward direction. It gives the position value of an element which is just situated before the traversed element into a list in reverse order that would be backed by a later call to previous( ) in a list. It returns (-1) if the cursor is positioned at the beginning of the list.

Parameter description

This method takes no argument.

Example of previousIndex( ) method

In this example we will show you how does previousIndex( ) method work in a collection using ListIterator interface. This example will help you to understand how can you find the index position of an element in backward direction into a collection. Through this example we will show you how previousIndex( ) method uses ListIterator object and how does it display index value from the list.

Example:-

package Devmanuals.com;
import java.util.LinkedList;
import java.util.ListIterator;
public class ListIteratorPreviousIndex {
  public static void main(String args[]) {
    LinkedList llist = new LinkedList();
    llist.add("A");
    llist.add("B");
    llist.add("C");
    llist.add("D");
    llist.add("E");
    System.out.println("List = " + llist);
    ListIterator litr = llist.listIterator();
    while (litr.hasNext())
      litr.next();
    while (litr.hasPrevious())
      System.out.println(litr.previous() " is at position "+ litr.previousIndex());
    System.out.println("Index of A is shown -1 because the cursor is positioned now at beginning of list");
  }
}

Output : 

List = [A, B, C, D, E]

E is at position 3

D is at position 2

C is at position 1

B is at position 0

A is at position -1

Index of A is shown -1 because the cursor is positioned now at beginning of list

Download Source code

Go to Topic «PreviousHomeNext»

Your Comment:


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

 
Tutorial Topics