标签:iterator rgs cti rgba void str bsp 结构 ide
任何容器的底层数据结构只有两种:一种是数组;另一种是链表。例如:list,set,map,二叉树,图等容器。访问容器使用Iterator迭代器。
public interface Collection_ { void add(Object o); int size(); Iterator_ iterator(); } public interface Iterator_ { boolean hasNext(); Object next(); } public class ArrayList_ implements Collection_{ private Object[] objects=new Object[10]; private int currentIdex=0; @Override public void add(Object o) { if(currentIdex==objects.length){ Object[] newObjects=new Object[objects.length * 2]; System.arraycopy(objects,0,newObjects,0,objects.length); objects=newObjects; } objects[currentIdex]=o; currentIdex++; } @Override public int size() { return currentIdex; } @Override public Iterator_ iterator() { return new CommenArrayList(); } public class CommenArrayList implements Iterator_{ private int index=0; @Override public boolean hasNext() { if(index>=currentIdex){ return false; } return true; } @Override public Object next() { Object o=objects[index]; index++; return o; } } } public class main { public static void main(String[] args) { Collection_ list=new ArrayList_(); for (int i = 0; i < 15; i++) { list.add(new String("你好"+i)); } //使用迭代器遍历 Iterator_ it=list.iterator(); while (it.hasNext()){ Object o=it.next(); System.out.println(o); } } }
jdk中的ArrayList也是如此设计。main方法中我们只需要更改ArrayList_,其它代码都不需要改变。
标签:iterator rgs cti rgba void str bsp 结构 ide
原文地址:https://www.cnblogs.com/zhaoyangxuan/p/14871050.html