Using Iterator for Lists : List « Utility Classes « SCJP






import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

class Dog {
  public String name;

  Dog(String n) {
    name = n;
  }
}

public class MainClass{
  public static void main(String[] args) {
    List<Dog> d = new ArrayList<Dog>();
    Dog dog = new Dog("A");
    d.add(dog);
    d.add(new Dog("B"));
    d.add(new Dog("C"));
    Iterator<Dog> i3 = d.iterator(); // make an iterator
    while (i3.hasNext()) {
      Dog d2 = i3.next(); // cast not required
      System.out.println(d2.name);
    }
    System.out.println("size " + d.size());
    System.out.println("get1 " + d.get(1).name);
    System.out.println("A " + d.indexOf(dog));
    d.remove(2);
    Object[] oa = d.toArray();
    for (Object o : oa) {
      Dog d2 = (Dog) o;
      System.out.println("oa " + d2.name);
    }
  }
}
A
B
C
size 3
get1 B
A 0
oa A
oa B








8.13.List
8.13.1.A List keeps it elements in the order in which they were added.
8.13.2.List: void add(int index, Object x) Inserts x at index.
8.13.3.List: Object get(int index) Returns the element at index.
8.13.4.List: int indexOf(Object x) Returns the index of the first occurrence of x, or -1 if the List does not contain x.
8.13.5.Collection: Object remove(int index) Removes the element at index.
8.13.6.ListIterator extends the Iterator interface to support bidirectional iteration of lists.
8.13.7.Using Iterator for Lists
8.13.8.toArray() method