索引越界?
Index out of Bounds?
Vertex [] vertices = new Vertex[n];
int [] numbers = new int[n*2];
AdjacencyList[] all = new AdjacencyList [n+1];
for (Vertex v : vertices)
{
System.out.println(v.value);
AdjacencyList a = new AdjacencyList(v);
for (int i = 0; i < n; i += 2)
{
if (numbers[i] == v.value){
a.connected[i] = vertices[i+1];//array index out of bounds exception:19
else { a.connected[i] = v; }
}
all[0] = a; //add the finished adjacency list to the array
}
在 n = 19 的情况下,我可以在代码中指示的位置得到索引越界错误。我不确定哪里出错了,因为一切都在 19
的范围内
vertices = 顶点列表 [1-19],
numbers 是一个扁平化的边数组
行中:
a.connected[i] = vertices[i+1];
您调用索引i+1
。这将导致 index out of bounds exception
。 (在您 n
等于 19 的示例中:有效索引将为 [0-18]。您的循环将从 0-18 开始。但是在该行中它会添加一个。18+1 = 19,这是一个无效索引)
在您的循环中将条件更改为:
for (int i = 0; i<n-1; i+=2){
要保证加一个的时候不会越界。
您的数组长度为 n=19,表示索引为 [0-18],i 增加 2。
所以当 i = 18 时,
a.connected[i] = vertices[i+1];
尝试访问不存在的顶点[19]。因此 ArrayOutOfBoundException。希望这有帮助。
Vertex [] vertices = new Vertex[n];
int [] numbers = new int[n*2];
AdjacencyList[] all = new AdjacencyList [n+1];
for (Vertex v : vertices)
{
System.out.println(v.value);
AdjacencyList a = new AdjacencyList(v);
for (int i = 0; i < n; i += 2)
{
if (numbers[i] == v.value){
a.connected[i] = vertices[i+1];//array index out of bounds exception:19
else { a.connected[i] = v; }
}
all[0] = a; //add the finished adjacency list to the array
}
在 n = 19 的情况下,我可以在代码中指示的位置得到索引越界错误。我不确定哪里出错了,因为一切都在 19
的范围内vertices = 顶点列表 [1-19], numbers 是一个扁平化的边数组
行中:
a.connected[i] = vertices[i+1];
您调用索引i+1
。这将导致 index out of bounds exception
。 (在您 n
等于 19 的示例中:有效索引将为 [0-18]。您的循环将从 0-18 开始。但是在该行中它会添加一个。18+1 = 19,这是一个无效索引)
在您的循环中将条件更改为:
for (int i = 0; i<n-1; i+=2){
要保证加一个的时候不会越界。
您的数组长度为 n=19,表示索引为 [0-18],i 增加 2。
所以当 i = 18 时,
a.connected[i] = vertices[i+1];
尝试访问不存在的顶点[19]。因此 ArrayOutOfBoundException。希望这有帮助。