首页 > 解决方案 > 索引超出范围?

问题描述

 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 是一个扁平的边数组

标签: javaarraysindexoutofboundsexception

解决方案


在行中:

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

您调用 index 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){

以确保添加一个时它不会超出范围。


推荐阅读