ArrayIndexOutofBounds 将元素添加到 Vector of Vector 的异常
ArrayIndexOutofBounds Exception from Adding Element to Vector of Vectors
我已经阅读了文档并查看了很多 SO 问题,但仍然无法在没有 运行 进入 ArrayIndexOutofBounds 异常的情况下创建向量的向量。对于某些上下文,我正在创建一个矩阵,其中每个槽都包含对边的引用,表示从源到目的地的航班。在 one SO response 之后,我按如下方式设置矢量。
Iterator<Edge> iter = array.iterator();
private Vector<Vector<Edge>> matrix = new Vector<Vector<Edge>>(9);
for (int i=0;i<9;i++){
matrix.add(i,new Vector<Edge>(9));
}
while (iter.hasNext()) {
Edge e = iter.next();
int s = e.source; //row
int d = e.destination; //col
Vector<Edge> row = matrix.get(s);
int size = row.size();
row.add(d, e); // Array Out of Bounds Exception
}
我相信我已经初始化了我的内部和外部向量,但不明白为什么向量的大小仍然为零。在开始放置和获取元素之前,是否必须将所有元素初始化为 null?我将衷心感谢您的帮助。
new Vector<Edge>(9)
创建容量为 9 的空 Vector
。因此,当 d
不为 0 时,为这样的 Vector
调用 add(d,e)
将抛出 ArrayIndexOutOfBoundsException
.
要用空值初始化每一行 Vector
,请使用:
for (int i = 0; i < 9; i++) {
Vector<Edge> v = new Vector<>(9);
matrix.add(v);
for (int j = 0; j < 9; j++)
v.add(null);
}
构造一个具有指定初始容量且容量增量为零的空向量。
参数:
initialCapacity 向量的初始容量
投掷:
java.lang.IllegalArgumentException如果指定初始容量为负
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}
我已经阅读了文档并查看了很多 SO 问题,但仍然无法在没有 运行 进入 ArrayIndexOutofBounds 异常的情况下创建向量的向量。对于某些上下文,我正在创建一个矩阵,其中每个槽都包含对边的引用,表示从源到目的地的航班。在 one SO response 之后,我按如下方式设置矢量。
Iterator<Edge> iter = array.iterator();
private Vector<Vector<Edge>> matrix = new Vector<Vector<Edge>>(9);
for (int i=0;i<9;i++){
matrix.add(i,new Vector<Edge>(9));
}
while (iter.hasNext()) {
Edge e = iter.next();
int s = e.source; //row
int d = e.destination; //col
Vector<Edge> row = matrix.get(s);
int size = row.size();
row.add(d, e); // Array Out of Bounds Exception
}
我相信我已经初始化了我的内部和外部向量,但不明白为什么向量的大小仍然为零。在开始放置和获取元素之前,是否必须将所有元素初始化为 null?我将衷心感谢您的帮助。
new Vector<Edge>(9)
创建容量为 9 的空 Vector
。因此,当 d
不为 0 时,为这样的 Vector
调用 add(d,e)
将抛出 ArrayIndexOutOfBoundsException
.
要用空值初始化每一行 Vector
,请使用:
for (int i = 0; i < 9; i++) {
Vector<Edge> v = new Vector<>(9);
matrix.add(v);
for (int j = 0; j < 9; j++)
v.add(null);
}
构造一个具有指定初始容量且容量增量为零的空向量。
参数:
initialCapacity 向量的初始容量
投掷:
java.lang.IllegalArgumentException如果指定初始容量为负
public Vector(int initialCapacity) {
this(initialCapacity, 0);
}