Get Previous and Next Index using Java ListIterator
Last Updated :
03 Apr, 2023
The previous index and next index in an ArrayList can be obtained using the methods previousIndex() and nextIndex() respectively of the ListIterator interface. previousIndex() can also return -1 if it at the beginning of the list.
Example:
Input: list = [2, 3, 6, 8]
listiterator is at the beginning find previous index.
Output: -1
Input: list = [2, 3, 6, 8]
listiterator is at the beginning find next index.
Steps to use previousIndex() and nextIndex():
- Create an empty ArrayList
- Add elements to ArrayList.
- Create a listiterator using listIterator() method.
Listiterator<Integer>iterator = arrList.listIterator();
- Now get the required index using the below commands
Syntax
iterator.previousIndex();
Returns: the index of the element that would be returned by a subsequent call to previous, or -1 if the list iterator is at the beginning of the list
Syntax
iterator.nextIndex();
Returns: the index of the element that would be returned by a subsequent call to next, or list size if the list iterator is at the end of the list
Example
Java
import java.io.*;
import java.util.ArrayList;
import java.util.ListIterator;
class PreviousAndNextIndex {
public static void main(String[] args)
{
ArrayList<Integer> arrList
= new ArrayList<Integer>();
arrList.add( 5 );
arrList.add( 10 );
arrList.add( 15 );
arrList.add( 20 );
arrList.add( 25 );
arrList.add( 30 );
System.out.println( "Initial arraylist =>"
+ arrList);
ListIterator<Integer> iterator
= arrList.listIterator();
System.out.println( "previous index =>"
+ iterator.previousIndex());
iterator.next();
iterator.next();
System.out.println( "Next index =>"
+ iterator.nextIndex());
}
}
|
Output:
Initial arraylist =>[5, 10, 15, 20, 25, 30]
previous index =>-1
Next index =>2
Time Complexity: O(n)
Auxiliary Space: O(1)
As constant extra space is used.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...