ArrayList底层分析及手写代码实现

刚才我写了个ArrayList的小demo

我对ArrayList的理解是可以放任意类型进去,然后可以进行动态扩容


接下来就放上我写的代码


public void add(T t){
    if(!checkSize()){
        capacity();
    }
    list[lastIndex++]=t;
    System.out.println(lastIndex);
}

数据我们存放到数组中,然后在放数据进去的时候判断数组是否有空间,没有就扩容

有就把最后一个索引++,然后放进去


接下来是检测大小的代码


public boolean checkSize(){
    if(lastIndex>=list.length){
        return false;
    }
    return true;
}

直接判断最后一个索引和数组的大小关系就行了


然后是扩容的代码

public boolean capacity(){
    Object[] result=new Object[lastIndex+lastIndex/2];
    copy(list,result);
    return true;
}

我们创建了一个新数组来存放数据,每次容量+当前数组容量的一半

然后执行复制操作


private void copy(Object[] list, Object[] result) {
    for(int i=0;i<list.length;i++){
        result[i]=list[i];
    }
    this.list=result;
}

遍历原来的数组然后放到新数组



接下来是获得数据的代码,做了简单的边界判断

public T get(int i){
    if(i>=0&&i<list.length){
        return (T) list[i];
    }
    try {
        throw new Exception(new IndexOutOfBoundsException());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}



接下来放上完整代码


public class List<T> {
    private Object[] list=new Object[2];
    private int lastIndex=0;

    public void add(T t){
        if(!checkSize()){
            capacity();
        }
        list[lastIndex++]=t;
        System.out.println(lastIndex);
    }

    public boolean checkSize(){
        if(lastIndex>=list.length){
            return false;
        }
        return true;
    }

    public boolean capacity(){
        Object[] result=new Object[lastIndex+lastIndex/2];
        copy(list,result);
        return true;
    }

    private void copy(Object[] list, Object[] result) {
        for(int i=0;i<list.length;i++){
            result[i]=list[i];
        }
        this.list=result;
    }

    public T get(int i){
        if(i>=0&&i<list.length){
            return (T) list[i];
        }
        try {
            throw new Exception(new IndexOutOfBoundsException());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}















猜你喜欢

转载自blog.csdn.net/u011546032/article/details/80386715