ArrayIndexOutOfBoundsException on a initialized Vector

有些话、适合烂在心里 提交于 2019-12-12 10:07:32

问题


I have this:

public class DoubleList<Key, Elem> implements ADTDoubleList<Key, Elem> {

    private Vector<Node<Key, Elem>> leftRight = new Vector<Node<Key, Elem>>(2);
    private int[] numLeftNumRight = new int[2];

    public DoubleList() {
        this.leftRight.set(0, null);
        this.leftRight.set(1, null);
        this.numLeftNumRight[0] = 0;
        this.numLeftNumRight[1] = 0;
    }
}

and it throws an ArrayIndexOutOfBoundsException.

I don't know why. Could someone help me?


回答1:


You can't set an element in a Vector or any other List if that index isn't already occupied. By using new Vector<Node<Key, Elem>>(2) you're ensuring that the vector initially has the capacity for two elements, but it is still empty and so getting or setting using any index won't work.

In other words, the list hasn't grown big enough for that index to be valid yet. Use this instead:

this.leftRight.add(null);  //index 0
this.leftRight.add(null);  //index 1

You could also do:

this.leftRight.add(0, null);
this.leftRight.add(1, null);


来源:https://stackoverflow.com/questions/5317406/arrayindexoutofboundsexception-on-a-initialized-vector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!