package pattern.iterator;
public class ArrayList<E> {
private Object[] elements;
private int index = 0;
public ArrayList() {
elements = new Object[10];
}
public void add(E e) {
if (index >= elements.length) {
Object[] newElements = new Object[elements.length * 2];
System.arraycopy(elements, 0, newElements, 0, elements.length);
elements = newElements;
}
elements[index++] = e;
}
public int size() {
return index;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("[");
Object e = null;
for (int i = 0; i < index; ++i) {
e = elements[i];
if (i < index - 1) {
sb.append(e.toString() + ",");
} else {
sb.append(e.toString() + "");
}
}
sb.append("]");
return sb.toString();
}
public Iterator<E> iterator() {
return new ArrayListIterator();
}
// Core
private class ArrayListIterator implements Iterator<E> {
private int currentIndex = 0;
public boolean hasNext() {
if (currentIndex >= index) {
return false;
} else {
return true;
}
}
@SuppressWarnings("unchecked")
public E next() {
return (E)(elements[currentIndex++]);
}
}
public static void main(String[] args) {
ArrayList<Node> al = new ArrayList<Node>();
for (int i = 0; i < 15; ++i) {
al.add(new Node("" + i, i));
}
System.out.println(al);
Iterator<Node> iter = al.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
}
}
class Node {
private String name;
private int age;
public Node(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "(" + name + "," + age + ")";
}
}