仿源码写一个简单的ArrayList

2017-01-06  本文已影响25人  Stringer

public class ArrayList01 {
    //数据结构:数组
    private Object[] elementData;
    //list中的元素个数
    private int size;

    public int size(){
        return this.size;
    }

    //构造函数
    public ArrayList01(){
        this(10);
    }

    public ArrayList01(int initialCapacity){
        if(initialCapacity<0){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        this.elementData=new Object[initialCapacity];
    }

    //获取
    public Object get(int index){
        rangeCheck(index);
        return elementData[index];
    }

    //修改
    public void set(int index,Object obj){
        rangeCheck(index);
        elementData[index]=obj;
    }

    //添加
    public void add(Object obj){
        ensureCapacity();
        elementData[size++]=obj;
    }

    public void add(int index,Object obj){
        rangeCheck(index);
        ensureCapacity();
        System.arraycopy(elementData,index,elementData,index+1,size-index);
        elementData[index]=obj;
        size++;
    }

    //删除
    public void remove(int index){
        rangeCheck(index);
        int numMoved=size-index-1;
        if(numMoved>0){
            System.arraycopy(elementData,index+1,elementData,index,numMoved);
        }
        elementData[--size]=null;
    }

    public void remove(Object obj){
        for(int i=0;i<size;i++){
            if(get(i).equals(obj)){
                remove(i);
            }
        }

    }

    //检查容量
    private void ensureCapacity(){
        if(size==elementData.length){
            Object[] newArray=new Object[size*2+1];
            System.arraycopy(elementData,0,newArray,0,elementData.length);
            elementData=newArray;
        }
    }
    
    //检查索引
    private void rangeCheck(int index){
        if(index<0||index>=size){
            try {
                throw new Exception();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ArrayList01 list=new ArrayList01(5);
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        list.add("ddd");
        list.add("eee");
        list.add("bbb");
        list.add("ggg");
        list.add(1,"ss");
        list.remove(0);
        list.set(0,"000");
        System.out.println(list.size());
        for(int i=0;i<list.size();i++){
            System.out.println(list.get(i));
        }

    }
}
上一篇下一篇

猜你喜欢

热点阅读