问题描述
我有这个:
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。
and it throws an ArrayIndexOutOfBoundsException.
我不知道为什么。有人可以帮帮我吗?
I don't know why. Could someone help me?
推荐答案
你不能在 Vector $ c中设置一个元素$ c>或任何其他
列表
如果该索引尚未被占用。通过使用 new Vector< Node< Key,Elem>>(2)
,您确保向量最初具有两个元素的容量 ,但它仍然是空的,所以获取
ting或设置
使用任何索引都不会起作用。
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 get
ting or set
ting 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
你也可以这样做:
this.leftRight.add(0, null);
this.leftRight.add(1, null);
这篇关于初始化Vector上的ArrayIndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!