Java 索引越界? Vertex[]顶点=新顶点[n]; 整数[]个数=新整数[n*2]; 邻接列表[]all=新邻接列表[n+1]; 对于(顶点v:顶点) { 系统输出打印项次(v值); 邻接列表a=新的邻接列表(v); 对于(int i=0;i

Java 索引越界? Vertex[]顶点=新顶点[n]; 整数[]个数=新整数[n*2]; 邻接列表[]all=新邻接列表[n+1]; 对于(顶点v:顶点) { 系统输出打印项次(v值); 邻接列表a=新的邻接列表(v); 对于(int i=0;i,java,arrays,indexoutofboundsexception,Java,Arrays,Indexoutofboundsexception,} 当n=19时,我会在代码中指出的点上得到一个索引越界错误。我不确定哪里出了错,因为一切都在19的范围内 顶点=顶点列表[1-19], 数字是直线中的一个扁平边阵列: Vertex [] vertices = new Vertex[n]; int [] numbers = new int[n*2]; AdjacencyList[] all = new AdjacencyList [n+1]; for (Vertex v : vertices) { System.out.print

}

当n=19时,我会在代码中指出的点上得到一个索引越界错误。我不确定哪里出了错,因为一切都在19的范围内

顶点=顶点列表[1-19], 数字是直线中的一个扁平边阵列

 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
调用索引
i+1
。这将导致
索引越界异常
(在
n
等于19的示例中:有效索引将为[0-18]。循环将从0-18开始。但在该行中,它将向其添加一个。18+1=19,这是一个无效索引) 在循环中,将条件更改为:

a.connected[i] = vertices[i+1];

for(int i=0;i您的数组具有长度,n=19,表示索引[0-18],i递增2

所以当我=18时

for (int i = 0; i<n-1; i+=2){

尝试访问不存在的顶点[19]。因此ArrayOutOfBoundException。希望这有帮助。

您调用
vertex[19+1]
(第20个索引,因此超出范围)可能与@MScoder5重复。不客气!如果答案解决了您的问题,请不要忘记接受答案(我不是指这个答案,只是为了将来)
 a.connected[i] = vertices[i+1];