Iterator(1)-ArrayList

来源:互联网 发布:淘宝秒杀不用刷新 编辑:程序博客网 时间:2024/06/01 20:12

    Iterator是设计模式中的一种,下面我们用一些jdk中的容器来诠释这种设计模式。

    今天聊的是ArrayList类的实现。

代码如下:

ArrayList.java:
public class ArrayList {Object[] objects = new Object[10];  //加入初始的基础容器为10,不过没关系可以自动扩展int index = 0;public void add(Object o) {   //这里的object可以指向任何对象if(index == objects.length) {   
                        //如果array中的10数装满了,我们再增长容器,这里是变为原来的2倍,但是jdk中实际的算法不是这样的Object[] newObjects = new Object[objects.length * 2];
</pre><pre name="code" class="java">                        //将数据拷贝到新的数组中System.arraycopy(objects, 0, newObjects, 0, objects.length); objects = newObjects;   //旧的ArrayList指向新的ArrayList}objects[index] = o;  //将对象放入容器中index ++;  //容器索引递增}public int size() {return index;}}


Cat.java:public class Cat {public Cat(int id) {super();this.id = id;}private int id;}


Test.java:public class Test {public static void main(String[] args) {ArrayList al = new ArrayList();  //ArrayListfor(int i=0; i<15; i++) {al.add(new Cat(i));  //add the object}System.out.println(al.size());  //show the Arraylist size}}

ok,arrylist模仿到这。

0 0