2

我有这个:

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;
    }
}

它抛出一个 ArrayIndexOutOfBoundsException。

我不知道为什么。有人可以帮助我吗?

4

1 回答 1

4

如果该索引尚未被占用,则不能在 aVector或任何其他中设置元素。List通过使用new Vector<Node<Key, Elem>>(2),您可以确保向量最初具有两个元素的容量,但它仍然是空的,因此使用get任何set索引都不起作用。

换句话说,该列表还没有增长到足以使该索引有效。改用这个:

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

你也可以这样做:

this.leftRight.add(0, null);
this.leftRight.add(1, null);
于 2011-03-15T20:12:44.030 回答