您的位置:首页 > 编程语言 > Java开发

java设计模式之iterator

2012-12-05 23:55 399 查看
Iterator模式:用于迭代容器中的所有元素。

先构建两个容器类,用于以后的实验:
建立一个ArrayList
public class ArrayList {
Object[] objects = new Object[10];
int index=0;
public void add(Object o ){
if(objects.length ==index ){
Object[] newobject = new Object[objects.length*2];
System.arraycopy(objects, 0, newobject, 0,objects.length );
objects = newobject;
}
objects[index]=o;
index++;
}

public int Size(){
return index;
}
}

Test类
public class Test {
public static void main(String args[]){
ArrayList a = new ArrayList();
for(int i=0;i<15;i++){
a.add(new Cat("Cafei",5));
}
System.out.println(a.Size());
}
}

下面建立一个LinkedList
关于LinkedList
LinkedList里面存放的是节点,节点里面存放的是数据与指向下一个节点的指针;
当添加数据的时候,将数据放到节点里面,如果是第一个数据,则节点的头节点与尾节点同时指向该节点。如果不是,则尾节点指向添加起来的节点,然后尾节点等于该节点
Node类
public class Node {
private Object date;
private Node next;

public Node(Object date, Node next) {
super();
this.date = date;
this.next = next;
}
public Object getDate() {
return date;
}
public void setDate(Object date) {
this.date = date;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}

}

LinkedList类
public class LinkedList {
Node head = null;
Node tail = null;
int size = 0;

public void add(Object o) {
Node n = new Node(o, null);
if (head == null) {
head = n;
tail = n;
}
tail.setNext(n);
tail = n;
size++;

}

public int size() {
return size;
}
}

考虑容器的可替换性,
统一里面的返回size()方法,定义Collection接口,里面定义add()方法及size方法
public interface Collection {
void add(Object o);
int size();
}
下面要统一其遍历方式,因为ArrayList与LinkedList的遍历方式是不一样的
定义一个接口,Iterator,提供两个方法next(), hasNext();
public interface Iterator {
Object next();
Boolean hasNext();
}
在容器类中实现其接口
@Override
public Iterator iterator() {

return new ArrayListIterator() ;
}

private class ArrayListIterator implements Iterator{
private int currentIndex=0;
@Override
public Object next() {
Object o= objects[currentIndex];
currentIndex++;
return o;
}

@Override
public Boolean hasNext() {
if(currentIndex>=index ) return false;
else return true;
}

}
该容器的内部类中实现其接口,
在Test类中的跌代方法如下
Iterator iterator = c.iterator();
while(iterator.hasNext()){
Object o=iterator.next();
System.out.print(o+" ");
}

程序结构图如下

Colletion接口统一其功能方法,如添加add(),反回大小size();
Iterator接口统一其遍历方法,iterator
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: