java - 索引超出范围?
问题描述
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];
您调用 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){
以确保添加一个时它不会超出范围。
推荐阅读
- python - 我想在 python 代码中使用 Dirac delta 作为时间函数来求解四个耦合微分方程。我没有做对
- google-apps-script - 如何通过 Google 表格中的二维数组通过 Apps 脚本插入 Big Query?
- java - Eclipse 项目不再导出可运行的 jar 文件
- php - Post ajax 在 IOS 和 MacOs 设备中不起作用
- flutter - 颤振:如何从颤振/提供者更改通知器中获取值
- gradle - 使用不同的 gradle 命令
- node.js - Buildpacks:有什么方法可以更改在“pack build”命令期间复制所有源代码的默认位置“/workspace”
- xmlhttprequest - 为谷歌登录过程执行 XMLHTTPRequest (POST) 时出现 404 错误
- arrays - 将矩阵旋转一个元素:是否有更简单/更简单的实现?
- reactjs - React Hook Pagination 解析超过 100 个组件