1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
/* Get Previous and next index using Java ListIterator Example This Java Example shows how to get previous and next index while traversing through elements of ArrayList using Java ListIterator. */ import java.util.ListIterator; import java.util.ArrayList; public class GetPreviousAndNextIndexListIteratorExample { public static void main(String[] args) { //create an object of ArrayList ArrayList aList = new ArrayList(); //Add elements to ArrayList object aList.add("1"); aList.add("2"); aList.add("3"); aList.add("4"); aList.add("5"); //Get an object of ListIterator using listIterator() method ListIterator listIterator = aList.listIterator(); /* Use nextIndex and previousIndex methods of ListIterator to get next and previous index from the current position in the list. */ System.out.println("Previous Index is : " + listIterator.previousIndex()); System.out.println("Next Index is : " + listIterator.nextIndex()); //advance current position by one using next method listIterator.next(); System.out.println("After increasing current position by one element : "); System.out.println("Previous Index is : " + listIterator.previousIndex()); System.out.println("Next Index is : " + listIterator.nextIndex()); } } /* Previous Index is : -1 Next Index is : 0 After increasing current position by one element : Previous Index is : 0 Next Index is : 1 */ |
Add Comment