gpt4 book ai didi

java - 获取 IndexOutOfBoundsException : -1 when no negative numbers are involved

转载 作者:行者123 更新时间:2023-12-02 02:29:58 27 4
gpt4 key购买 nike

我一直在创建一个图来运行 A* 的实现,但在查找节点的邻居时,我似乎遇到了某个错误。我的逻辑是,在表示邻接矩阵的 2D ArrayList 中,列表 1 中包含节点 a b c d,列表 2 中包含节点 a b c d,并且它们相遇的索引应具有非 0 的值,以表明存在边缘。这就是我在这里尝试做的事情:

public List<Node> neighbours(Node a){
List<Node> neighbours = new ArrayList<Node>();
for(int i = 0; i < nodes.size() - 1; i ++){
int n = matrix.get(matrix.indexOf(a)).get(i);
if (n != 0){
neighbours.add(nodes.get(i));
}
}
return neighbours;
}

但是我得到了一个不错的 Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1错误,我已经盯着这个看了 30 分钟,但我不知道这个 -1 来自哪里。我还将添加用于构建矩阵的代码,因为这可能提供线索:

public void addNode (Node a){
int count = 0;
nodes.add(a);
matrix.add(new ArrayList<Integer>(nodes.size()));
for (List<Integer> list : matrix){
count++;
int diff = Math.abs(nodes.size() - list.size());
if (diff != 0){
for (int i = 0; i < diff; i ++)
matrix.get(count-1).add(0);
}
}
}

每次添加节点时,我都会更新矩阵的大小。我希望这不是答案就在我面前但我太累了而看不到的情况。感谢您的帮助!

最佳答案

您确定值 a 在矩阵中吗?如果没有那么

matrix.indexOf(a)

如果找不到该值,可能会返回 -1。

关于java - 获取 IndexOutOfBoundsException : -1 when no negative numbers are involved,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47263609/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com