public
ListIterator<E> listIterator(int index)
Returns
a list-iterator of the elements in this list (in proper sequence),
starting at the specified position in the list.
import java.util.*; class LinkedListIterator{ public static void main(String args[]){ LinkedList<Integer> myList; myList = new LinkedList<> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); myList.add(50); ListIterator iter = myList.listIterator(2); System.out.println("List iterator from index 2"); System.out.println("Elements in forward direction"); while(iter.hasNext()){ System.out.println(iter.next()); } System.out.println("Elements in backward direction"); while(iter.hasPrevious()){ System.out.println(iter.previous()); } } }
Output
List iterator from index 2 Elements in forward direction 30 40 50 Elements in backward direction 50 40 30 20 10
1. Throws
IndexOutOfBoundsException if index out of range
import java.util.*; class LinkedListIteratorIndexOut{ public static void main(String args[]){ LinkedList<Integer> myList; myList = new LinkedList<> (); /* Add Elements to myList */ myList.add(10); myList.add(20); myList.add(30); myList.add(40); myList.add(50); System.out.println("List iterator from index 6"); ListIterator iter = myList.listIterator(6); } }
Output
List iterator from index 6 Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size:5 at java.util.LinkedList.checkPositionIndex(LinkedList.java:558) at java.util.LinkedList.listIterator(LinkedList.java:865) at LinkedListIteratorIndexOut.main(LinkedListIteratorIndexOut.java:16)
No comments:
Post a Comment