设计模式02迭代器(java)
先贴代码,有空来写内容。
1.定义集合
import java.util.List;
import java.util.ArrayList;
1 //coollection是我自己定义的一个集合,因为要写迭代器,得有个迭代的对象啊。 2 class coollection<Object>{ 3 //coollection的数据存储在一个ArrayList里 4 private List<Object> data = new ArrayList<Object>(); 5 //index用于记录当前将迭代元素的下标 6 private int index = 0; 7 //给集合添加元素 8 public void add(Object o){ 9 data.add(o); 10 } 11 //获取index 12 public int getCurrent(){ 13 return index; 14 } 15 //获取集合规模 16 public int size(){ 17 return data.size(); 18 } 19 //获取一个元素并将索引指向下一个元素 20 public Object get(){ 21 return data.get(index++); 22 } 23 //删除已经被迭代的最后一个元素 24 public void remove(){ 25 if(index != 0) 26 data.remove(index-1); 27 } 28 //获取coollection的迭代器 29 public iterator getiterator(){ 30 index = 0; 31 return new coollectionItrator(this); 32 } 33 }
2.写迭代器
1 //迭代器接口,所有迭代器都要实现这个接口的所有功能 2 interface iterator{ 3 public boolean hasNext(); 4 public Object next(); 5 public void remove(); 6 } 7 //coollection集合的专属迭代器,实现了iterator 8 class coollectionItrator implements iterator{ 9 //定义该迭代器要操作的集合 dataSrc 10 coollection<Object> dataSrc; 11 //初始化集合 12 public coollectionItrator(coollection c){ 13 dataSrc = c; 14 } 15 //重写hasNext() 16 @Override 17 public boolean hasNext(){ 18 return dataSrc.size() > dataSrc.getCurrent(); 19 } 20 //重写next() 21 @Override 22 public Object next(){ 23 return dataSrc.get(); 24 } 25 //重写remove() 26 @Override 27 public void remove(){ 28 dataSrc.remove(); 29 } 30 }
3.测试迭代器
1 // 测试迭代器 2 public class iteratorDemo{ 3 public static void main(String[] args){ 4 //new 一个集合,将三个实例放进集合里 5 coollection<Student> stu = new coollection<Student>(); 6 stu.add(new Student("singleDog","man","18")); 7 stu.add(new Student("singleDoge","feman","19")); 8 stu.add(new Student("0.0","feman","20")); 9 10 //获取集合stu的迭代器 11 iterator it = stu.getiterator(); 12 //遍历集合并输出元素 13 while(it.hasNext()){ 14 System.out.println(it.next()); 15 } 16 // 测试迭代器的remove功能 17 it.remove(); 18 System.out.println("删除后:"); 19 it = stu.getiterator(); 20 while(it.hasNext()){ 21 System.out.println(it.next()); 22 } 23 } 24 }

浙公网安备 33010602011771号