为什么抛出ArrayStoreException?

时间:2016-08-15 12:10:36

标签: java

我正在尝试编写自己的ArrayList类。

我的代码如下:

package test;
import java.util.Arrays;
import java.util.*;

public class MyArrayList {
    private Object[] objects = null;
    private int currentSize = 0;

    public void add(Object obj) {
        increaseSize();
        objects[currentSize++] = obj;
    }

    public Object get(int index) {
        if (currentSize >= index) 
            return objects[index];
        else 
            throw new ArrayIndexOutOfBoundsException();
    }

    public void remove(int index) {
        if (currentSize >= index) {
            for (int i = index; i < currentSize; i++) {
                objects[i] = objects[i + 1];
            }
            objects[currentSize--] = null;
        }
        else throw new ArrayIndexOutOfBoundsException();
    }

    public int size() {
        return currentSize;
    }

    private void increaseSize() {
        if (objects == null) objects = new Objects[1];
        else objects = Arrays.copyOf(objects, objects.length + 1);
    }

    public static void main(String args[]) {
        MyArrayList l = new MyArrayList();
        Integer integ = new Integer(1);
        l.add(integ);
        for (int i = 0; i < l.size(); i++)
        System.out.println("Element " + i + " = " + l.get(i));
    }
}

如果我尝试初始化increaseSize()中的对象,我会得到ArrayStoreException。如果我在开始时初始化对象,我就不再得到该异常了。

有人可以解释一下这个原因吗?

2 个答案:

答案 0 :(得分:3)

您正在创建一个Objects类型的数组:

if (objects == null)
    objects = new Objects[1];

Objectsjava.util.Objects,因为您已从java.util导入了所有内容:

import java.util.*;

虽然你可能意味着一组Object s:

if (objects == null)
    objects = new Object[1];

当您尝试在数组中存储某些内容时会发生错误 - 遗憾的是,Java中的数组类型是协变的,这会导致类似的问题。

答案 1 :(得分:1)

您的问题是一个非常简单的错误:

您不是创建Object数组,而是创建Object s

这样只允许存储Objects对象。因此,当您尝试添加Integer对象时,会为您提供ArrayStoreException。因为Integer不是Objects对象。 (java.lang.Objects是一个具有一些静态辅助方法的实用程序类)。

所以,只需改为:

vkGetInstanceProcAddr