java 自定義一個容器類

 
public class ArrayList {
    public int index = 0;
    Object[] objects = new Object[2];
    public void add(Object o) {
        //當index超出最初定義數組的長度時,自動擴容
        if(index == objects.length){
            System.out.println("extend................");
            Object[] newObjects = new Object[objects.length * 2];
            for (int i = 0; i < index; i++) newObjects[i] = objects[i];
            objects = newObjects;
        }
        objects[index] = o;
        index++;
    }

    public int size(){ return index; }

    public int get(int i) {return (int)objects[i]; }

    public static void main(String[] args) {
        ArrayList a = new ArrayList();
        a.add(23);
        a.add(67);
        a.add(98);
        a.add(989);
        a.add(9897);
        for (int i = 0; i < a.size(); i++)
            System.out.println(a.get(i));
//        for (Integer abc : a) {
//            System.out.println(abc);
//        }
    }
}
相關文章
相關標籤/搜索