Java设计模式_Iterator(迭代容器)

来源:互联网 发布:ubuntu安装万能五笔 编辑:程序博客网 时间:2024/05/29 18:37

方法一:

采用ArrayList类实现.

 

/**

 * 此数组类可动态扩展(方法一)

 * @author tfq

 *

 */

public class ArrayList {

 

Object[] objects=new Object[10];

int index=0;

/**

* 父类引用指向子类对象

* @param o

*/

public void add(Object o){

if(index==objects.length){

Object[] newObjects=new Object[objects.length*2];

System.arraycopy(objects, 0, newObjects, 0, objects.length);

objects=newObjects;

}

objects[index]=o;

index++;

}

/**

* 获取数组的长度

* @return

*/

public int size(){

return index;

}

}

 

/*

*

*辅助类

/

public class Dog {

 

private int id;

public Dog(int id){

super();

this.id=id;

}

}

public class Test {
public static void main(String[] args) {
   ArrayList arr=new ArrayList();
   for(int i=0;i<1000;i++){
arr.add((Object)new Dog(10));
    }
    System.out.println(arr.size());
  }
}
打印出数组的长度:1000
方法二:
采用动态链表方式
public class LinkedList {
Node head=null;
Node tail=null;
int index=0;
public void add(Object o){
Node n=new Node(o,null);
if(head==null){
head=n;
tail=n;
}
tail.setNext(n);
tail=n;
index++;
}
public int size(){
return index;
}
}
///结点类
public class Node {
private Object data;
private Node next;
public Node(Object data, Node next) {
super();
this.data = data;
this.next = next;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
public class Test {
public static void main(String[] args) {
LinkedList lkl=new LinkedList();
for(int i=0;i<1000;i++){
lkl.add((Object)new Dog(10));
}
System.out.println(lkl.size());
    }
}
打印采用链表方式生成的Iterator长度:1000