java.lang.ArrayIndexOutOfBoundsException : 48

标签 java arrays indexoutofboundsexception dijkstra

我有一个 Dijkstra 算法练习,当我运行我的程序时,出现以下错误: 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 48
怎么了?我无法发送整个代码,因为它有 200 行。但问题出现在cmd中的那些行
dist[i] = Integer.MAX_VALUE;和 距离[i] = 0;

预先感谢您的帮助。

public static void DijkstraOnNode (int start) {

  int[] dist = new int [myNodes.size()]; //where myNodes is an ArrayList of Hashset<Link>
                                         //and Link is a class that contains node kai weight       
  int[] pred = new int [myNodes.size()];  
  int[] pq = new int [myNodes.size()];

 for (int i = 0; i <= myNodes.size(); i++) {

    if (i!= start)
        dist[i] = Integer.MAX_VALUE;
    else
        dist[i] = 0;

   pq[i] = dist[i];
}

(代码继续)

最佳答案

for (int i = 0; i <= myNodes.size(); i++) 

这会导致问题 将其更改为

for (int i = 0; i < myNodes.size(); i++) 

因为,假设 myNodes.size() 返回 8,并且您试图到达 dist[8],但 dist[] 数组从 0 开始,到 7 结束.

关于java.lang.ArrayIndexOutOfBoundsException : 48,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23065508/

相关文章:

java - 从字符串标记器获取值

C++ 将数组复制到指针参数

python - 如何在 Python 中创建一个对象数组?

c# - 在 C# 中使用 LINQ 进行分组 - 索引越界

java - 在一组带组的多个限制器之间提取字符串

java - 我们可以将带有setter和getter的类称为Java Bean吗?

java - 如何限制通过 ObjectInputStream 从 Socket 读取的最大大小?

java - 升级到 JBoss EAP 后 CXF 不工作

c++ - 覆盖静态成员和 "static static arrays"

java - 我试图通过迭代用整数填充数组,但出现 ArrayIndexOutOfBoundsException