手撕ArrayList

不多BB,直接上代碼:

public class MyArrayList {
    //創建數組對象
    private Object[] elements;
    //已使用數組長度
    private int size = 0;
    //初始化數組長度
    private final static int INIT_LENGTH = 10;
    //數組最大長度
    private int static int MAX_LENGTH = Integer.MAX_VALUE;

    //無參構造方法
    public MyArrayList() {
        this(INIT_LENGTH);
    }

    //有參構造方法
    public MyArrayList(int capacity) {
        if (capacity < 0) {
            System.out.println("創建集合失敗");
        }
        elements = new Object[capacity];
    }

    //獲取已使用數組長度
    public int size() {
        return size;
    }

    //判斷數組是否爲空
    public boolean isEmpty() {
        return size == 0;
    }

    //添加數組元素
    public void add(E e) {
        checkCapacity(size);
        elements[size++] = e;
    }

    //指定位置添加元素
    public void add(int index, E e) {
        checkRange(index);
        checkCapacity(size);
        System.arraycopy(elements, index, elements, index + 1, size - index);
        elements[index] = e;
        size++;
    }

    //查找指定元素
    public E get(int index) {
        checkRange(index);
        return elements[index];
    }

    //刪除指定元素
    public E remove(int index) {
        checkRange(index);
        int moveSize = size - index - 1;
        E value = get(index);
        //判斷是否爲數組最後一個元素
        if (moveSize > 0) {
            System.arraycopy(elements, index + 1, elements, index, moveSize);
        }
        elements[size--] = null;
        return value;
    }

    //檢查數組下標是否越界
    public void checkRange(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("數組下標越界");
        }
    }

    //檢查是否需要擴容
    public void checkCapacity(int size){
        if(size ==  elements.length){
            int newLength = size<<1 < MAX_LENGTH ? size<<1 : MAX_LENGTH;
            elements = Arrays.copyOf(elements, newLength);
        }
    }
}
    

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章