Java .

Java ListIterators

java.util.ListIterator

creating a ListIterator

ListIterator listIteratorName = arrayListName.listIterator();
//creating a ListIterator for an ArrayList

ListIterator listIteratorName = linkedListName.listIterator(); //creating a ListIterator for a LinkedList

ListIterator listIteratorName = listName.listIterator(); //creating a ListIterator for a List

ListIterator methods to find out things about the ArrayList

boolean areThereMore = listIteratorName.hasNext();

int whereIsNext = listIteratorName.nextIndex();

boolean wereThereAny = listIteratorName.hasPrevious();

int whereIsPrevious = listIteratorName.previousIndex();

ListIterator methods to retrieve elements

ClassTypeToCastTo nextElement = 
  (ClassTypeToCastTo) listIteratorName.next();

ClassTypeToCastTo previousElement = (ClassTypeToCastTo) listIteratorName.previous();

ListIterator methods which alter what is in the underlying ArrayList, LinkedList, or List

arrayListName.add(elementToAdd);
//inserts before what next() would return

arrayListName.set(intOffsetToSetElementAt, objectIn); //replaces element that was just returned by next() or previous(), // can not be called after add.

arrayListName.remove(intOffsetToRemoveElement); //deletes element that was just returned by next() or previous(), // can not be called after add.

Using a ListIterator to traverse an existing ArrayList

                          
ListIterator listIteratorName = arrayListName.listIterator();

while (listIteratorName.hasNext()) { classTypeToCastTo nextElement = (ClassTypeToCastTo) listIteratorName.next(); }

References


online
The Java 2 Platform Specification
Books
Thinking in Java by Bruce Eckel
Core Java (TM) 2 Volume 1 - Fundamentals by Cay Horstmann and Gary Cornell
Comments
Sign in to be the first to comment on Java ListIterators.