ArrayIndexOutofBounds从向向量的向量添加元素的异常 [英] ArrayIndexOutofBounds Exception from Adding Element to Vector of Vectors
问题描述
我已经阅读了文档并查看了几十个SO问题,但是如果不遇到ArrayIndexOutofBounds异常,仍然无法创建向量的向量.在某些情况下,我正在创建一个矩阵,其中每个插槽都包含对边缘的引用,表示从源到目的地的飞行.遵循一个SO响应,我如下设置我的向量.
I've read the documentation and looked at scores of SO questions and still can't create a vector of vectors without running into the ArrayIndexOutofBounds exception. For some context, I am creating a matrix, where each slot contains a reference to an edge, representing a flight from a source to a destination . Following one SO response, I set up my vector as follows.
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?我将衷心感谢您的帮助.
I believe I have initialized my inner and outer vectors and don't understand why the size of the vector is still zero. Do I have to initialize all the elements to null before I can start putting and getting elements? I would really appreciate your help.
推荐答案
新Vector< Edge>(9)
创建容量为9的空 Vector
.因此,调用当 d
不为0时,此类 Vector
的 add(d,e)
会抛出 ArrayIndexOutOfBoundsException
.
new Vector<Edge>(9)
creates an empty Vector
of capacity 9. Therefore, calling add(d,e)
for such a Vector
when d
is not 0 will throw ArrayIndexOutOfBoundsException
.
要使用空值初始化每行 Vector
,请使用:
To initialize each row Vector
with null values, use:
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);
}
这篇关于ArrayIndexOutofBounds从向向量的向量添加元素的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!