在Java中创建一个模仿ArrayList的类

时间:2018-03-26 23:00:17

标签: java arraylist

我正在尝试创建一个模仿某些ArrayList<Integer>行为的类。

当我尝试增加容量或原始数组int[] arr1

时,我使用int[] tempArr存储数组元素和arr1临时存储空间

这不起作用。那么您认为我可以使用的另一种方法是什么呢?

以下是我的代码:请参阅public void add

public class ArrayListLike implements ArrayListLikeInterface {


    public int capacity = 0; // The capacity of the array list (ArrayListLike)
    private static final int INIT_CAPACITY = 10; // Initial capacity
    private int size = 0;  // Initial size
    private int[] arr;
    private int[] tempArr;
    private int count = 0;


    // Constructors
    public ArrayListLike() {
        arr = new int[INIT_CAPACITY];
        capacity = INIT_CAPACITY;
    }



    public void add(Integer element) {
        // TODO Auto-generated method stub
        if (count == capacity) {
            tempArr = new int[capacity];
            System.arraycopy(arr, 0, tempArr,0, capacity);
            capacity *= 2;
            arr = null;
            arr = new int[capacity];
            System.arraycopy(tempArr, 0, arr,0, capacity);
            arr[count] = element;
            count++;
        } else {
            arr[count] = element;
            count++;
        }
    }

    public int get(int index) {
        // TODO Auto-generated method stub
        if (index <=  capacity) {
            return arr[index];
        } else {
            throw new ArrayIndexOutOfBoundsException(index);
        }
    }

    public int size() {
        // TODO Auto-generated method stub
        size = arr.length;
        return size;
    }


}

这是主要的课程

public class Main {

    public static void main(String[] args) {
    // write your code here
        ArrayListLike arr1 = new ArrayListLike();
        System.out.println(arr1.size());

        arr1.add(0);
        arr1.add(1);
        arr1.add(2);
        arr1.add(3);
        arr1.add(4);
        arr1.add(5);
        arr1.add(6);
        arr1.add(7);
        arr1.add(8);
        arr1.add(9);
        arr1.add(10);
    }
}

这是错误:

Exception in thread "main" 10
java.lang.ArrayIndexOutOfBoundsException
    at java.base/java.lang.System.arraycopy(Native Method)
    at hw5sol.ArrayListLike.add(ArrayListLikeInterface.java:31)
    at hw5sol.Main.main(Main.java:21) 

1 个答案:

答案 0 :(得分:0)

当您将旧数组复制到新数组时,使用新容量大小为20而temp只有10个元素,因此当它尝试下次复制时会抛出ArrayIndexOutOfBoundsException元件。

public void add(Integer element) {
    // TODO Auto-generated method stub
    if (count == capacity) {
        tempArr = new int[capacity];
        System.arraycopy(arr, 0, tempArr,0, capacity);
        capacity *= 2;
        arr = null;
        arr = new int[capacity];
//Here!!
        System.arraycopy(tempArr, 0, arr,0, tempArr.length);
        arr[count] = element;
        count++;
    } else {
        arr[count] = element;
        count++;
    }
}