我正在尝试实现合并排序,但我不断收到 IndexOutOfBoundsException
并且我无法找出原因。
我已经调试了我的程序,并且在此函数中我从未使用无效索引访问数组。引发异常的行也与抛出异常的数组 a
无关。
所以这是抛出异常的函数:
private static int[] merge(int[] a, int[] b){
int[] res = new int[a.length + b.length];
int ia = 0;
int ib = 0;
int i = 0;
while(ia < a.length || ib < b.length){
if(ia < a.length && a[ia] < b[ib]) {
res[i] = a[ia];
ia++;
i++; //this is the line causing the exception
}
else {
res[i] = b[ib];
ib++;
i++;
}
}
return res;
}
我是否缺少一些 Java 特定行为?如果是这样,我该如何解决这个问题?
我也知道我不应该再在 java 中使用数组,但我所在的类禁止任何其他容器。
最佳答案
指令i++
不能导致IndexOutOfBoundsException
。与 JVM 中运行的代码相比,您很可能在编辑器中调试不同的代码(例如,新代码已编辑但未构建)。重建您的 Java 代码并确保您在编辑器中可见并在 JVM 中运行相同的代码,以便行号对齐。
关于java - IndexOutOfBoundsException 不访问数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470768/