ListIterator<E>
listIterator(int index)
Returns
a list iterator over the elements in this list (in proper sequence),
starting at the specified position in the list.
import java.util.*; class listIteratorFromIndex{ public static void main(String args[]){ List<Integer> myList = new LinkedList<> (); /* Add Elements to myList */ for(int i=0; i < 15; i++) myList.add(i); /* traverse the list in Forward */ ListIterator<Integer> iter1 = myList.listIterator(5); ListIterator<Integer> iter2 = myList.listIterator(5); System.out.println("Elements in myList are\n" + myList); System.out.println("\nForward Traversal Of the List from index 5"); while(iter1.hasNext()){ System.out.print(iter1.next() + " "); } System.out.println(); /* traverse the list in Backward */ System.out.println("\nBackward Traversal Of the List from index 5"); while(iter2.hasPrevious()){ System.out.print(iter2.previous() + " "); } System.out.println(); } }
Output
Elements in myList are [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] Forward Traversal Of the List from index 5 5 6 7 8 9 10 11 12 13 14 Backward Traversal Of the List from index 5 4 3 2 1 0
1. throws
IndexOutOfBoundsException if the index is out of range
import java.util.*; class listIteratorIndexBound{ public static void main(String args[]){ List<Integer> myList = new LinkedList<> (); /* Add Elements to myList */ for(int i=0; i < 15; i++) myList.add(i); /* traverse the list in Forward */ ListIterator<Integer> iter1 = myList.listIterator(16); } }
Output
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 16, Size: 15 at java.util.LinkedList.checkPositionIndex(Unknown Source) at java.util.LinkedList.listIterator(Unknown Source) at listIteratorIndexBound.main(listIteratorIndexBound.java:12)
No comments:
Post a Comment