自己实现ArrayList

2018-07-06  本文已影响8人  Captain_w

ArrayList最重要的基本方法Api:

set(int idx, AnyType newVak)

向目标索引idx设置值 newVal

 public AnyType set(int idx, AnyType newVal) {
        if (idx < 0 || idx >= size()) {
            throw new ArrayIndexOutOfBoundsException();
        }
        AnyType old = theItems[idx];
        theItems[idx] = newVal;
        return old;
    }

get(int idx)

读取目标索引idx的值

   public AnyType get(int idx) {
        if (idx < 0 || idx >= size()) {
            throw new ArrayIndexOutOfBoundsException();
        }
        return theItems[idx];
    }

ensureCapacity(int newCapacity)

可以叫扩容为newCapacity方法.

    public void ensureCapacity(int newCapacity) {
        /*theSize 数组实际大小*/
        if (newCapacity < theSize) {
            return;
        }
        /*创建新的数组,然后复制老数组值入新数组*/
        AnyType[] old = theItems;
        theItems = (AnyType[]) new Object[newCapacity];
        for (int i = 0; i < size(); i++) {
            theItems[i] = old[i];
        }
    }

size()

返回list的大小

    public int size() {
        return theSize;
    }

add()

添加元素

 public boolean add(AnyType x) {
        add(size(), x);
        return true;
    }

    public void add(int idx, AnyType x) {
        /*当存值得数组大小和list大小相等时,把存值数组扩容为1倍*/
        if (theItems.length == size()) {
            ensureCapacity(2 * theItems.length);
        }
        /*如果是在数组中间插入,后面的元素要向高位移动*/
        for (int i = theSize; i > idx; i--) {
            theItems[i] = theItems[i - 1];
        }
        theItems[idx] = x;
        theSize++;

    }

remove(int idx)

删除指定位置的元素


    public AnyType remove(int idx) {
        AnyType removeItem = theItems[idx];
        /*如果删除的元素是不是尾,那就需要高位向前移动*/
        for (int i = idx; i < size() - 1; i++) {
            theItems[i] = theItems[i + 1];
        }
        theSize--;
        return removeItem;
    }
上一篇下一篇

猜你喜欢

热点阅读