Iterator模式
主要是用在容器的遍历上,其他的地方都不怎么用;理解一下,会用了就可以了;
 

1、背景                    

请动手自己写一个可以动态添加对象的容器;
代码:
ArrayList.java(是自己实现的,不是JDK)
package com.cy.dp.iterator;

public class ArrayList {
    Object[] objects = new Object[10];
    int index = 0;                                        //objects下一个空的位置
    
    /**
     * 如果数组容量已满,这里简单处理,扩容为原来的两倍;
     * sun的做法是有一个加权值,根据原来的容量,加上多少...
     * @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++;
    }
    
    public int size(){
        return index;
    }
    
}

Cat.java  辅助类:

package com.cy.dp.iterator;

public class Cat {
    private int id;

    public Cat(int id) {
        super();
        this.id = id;
    }
}
View Code

Test.java 测试类:

package com.cy.dp.iterator;

import com.cy.dp.iterator.ArrayList;

public class Test {
    public static void main(String[] args) {
        ArrayList al = new ArrayList();
        for(int i=0; i<15; i++){
            al.add(new Cat(i));
        }
        System.out.println(al.size());
    
        
    }
}
View Code

相关文章:

  • 2021-12-20
  • 2022-12-23
  • 2022-02-06
  • 2021-12-07
  • 2021-09-23
  • 2021-12-22
  • 2021-08-28
猜你喜欢
  • 2021-12-05
  • 2021-08-25
  • 2021-10-22
  • 2021-08-10
  • 2022-02-12
  • 2021-10-02
相关资源
相似解决方案