逛奔的蜗牛

我不聪明,但我会很努力

   ::  :: 新随笔 ::  ::  :: 管理 ::


package pattern.iterator;


public interface Iterator<E> {

boolean hasNext();

E next();

}



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 + ")";

}

}


posted on 2009-11-06 02:18 逛奔的蜗牛 阅读(187) 评论(0)  编辑 收藏 引用 所属分类: Java

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理