仿源码写一个简单的ArrayList


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){
            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

你可能感兴趣的:(仿源码写一个简单的ArrayList)