Anda di halaman 1dari 5

Iterator and ListIterator in Java

Iterator enables us to iterate over or traverse a collection


Iterator is an interface (in java.util)
It contains only three methods:
hasNext()
next()
remove()
Most collections have an iterator() method that will return an implementation of these methods

Iterator it = list.iterator();
while (it.hasNext())
System.out.println(it.next());

for (Object element : list)


System.out.print(element + " ");

Vector v=new Vector();


System.out.println("Before adding elements:");
System.out.println("Capacity=" + v.capacity()) ;
System.out.println("size="+ v.size());
v.addElement(1);
v.addElement(2);
v.addElement(3);
v.add(1, 4);
System.out.println("After adding elements:");
Iterator listItr = v.iterator();
while (listItr.hasNext()) {
System.out.println(listItr.next() + " ");
}
System.out.println("capacity=" + v.capacity());
System.out.println("Size = "+v.size());

LinkedList myList = new LinkedList();


myList.add("alpha");
myList.add(0,"beta");
myList.add("gama");
myList.add(2,"delta");
myList.add("alpha");
myList.remove(1);
myList.remove("delta");
myList.remove(2);
for (Object element : myList)
System.out.print(element + " ");
A ListIterator has the usual Iterator methods:
hasNext(), next(), and remove(),
but it also has methods such as:
-hasPrevious()
-previous()
-add(obj)
that make it possible to move backwards in the list and to add an item at the current position of the
iterator.

Iterator

ListIterator
+add(o: Obj ect) : void Adds the s pecifi ed object to the list
+hasPrevious() : boolean Return s tru e if this list iterator has more elements
when traversing backward.
+next Index() : int Return s the i ndex of the next element
+previousIndex() : i nt Return s the i ndex of the previosu element
+previous() : Ob ject Return s the p revious el ement i n this list iterator
+set(o: Object ) : void Replaces the l ast elemen t returned b y the previ ous
or next method with t he specified elem ent

List lList = new LinkedList();


lList.add("red");
lList.add(0,"green");
lList.add("blue");
lList.add(1,"yellow");
lList.remove(3);
ListIterator listItr = lList.listIterator();
while (listItr.hasNext()) {
System.out.println(listItr.next() + " ");
}
System.out.println();
listItr = lList.listIterator(lList.size());
while (listItr.hasPrevious()) {
System.out.println(listItr.previous() + " ");
}

Output:

green
yellow
red

red
yellow
green

Anda mungkin juga menyukai