动态数组

76 阅读1分钟

java自带数据是不能对数组进行插入和删除的,创建数组时就已经固定死了,不能再改变,即静态数组

向最后位置 [size] 添加元素

public void add(int index, int element) { checkAndGrow();

    // 添加逻辑
    if (index >= 0 && index < size) {
        // 向后挪动, 空出待插入位置
        System.arraycopy(array, index,
                array, index + 1, size - index);
    }
    array[index] = element;
    size++;
}

容量检查

private void checkAndGrow() {
        // 容量检查
        if (size == 0) {
            array = new int[capacity];
        } else if (size == capacity) {
            // 进行扩容, 1.5 1.618 2
            capacity += capacity >> 1;
            int[] newArray = new int[capacity];
            System.arraycopy(array, 0,
                    newArray, 0, size);
            array = newArray;
        }