【发布时间】:2019-05-24 09:38:28
【问题描述】:
所以我有一个 android 应用程序并且经常强制关闭。为什么在我的 logcat 上,以下方法经常会导致错误?
static void solveTSP(int[][] valuesMatrix) {
shortestDistance = Integer.MAX_VALUE;
longestDistance = Integer.MIN_VALUE;
shortestPath = null;
int totalPlaces = valuesMatrix.length;
ArrayList<Integer> places = new ArrayList<>();
for(int i=0; i<totalPlaces; i++){
places.add(i);
}
int startPlace = places.get(0);// in logcat, this line is the cause of the Index error Out of Bounds Exception: Invalid index 0, size is 0. How does that happen?
int currentDistance = 0;
bruteForceSearch(valuesMatrix, places, startPlace, currentDistance);
}
【问题讨论】:
-
在你的 for 循环上放一个断点...检查你的 arratList 是否真的被填充了
-
你理解错误信息吗?
-
totalPlaces 为 0,因此 id 不会进入 for 循环,places 是空列表,当您尝试查找空列表的第一个元素时会抛出错误
-
您将哪个参数传递给该方法?我猜是一个空数组,所以
valuesMatrix.length为0,for 循环没有被执行,所以places和get(0)没有添加任何内容。 -
错误中明确提到 valuesMatrix 的大小为零,因此当您尝试获取其他元素时,它会引发相同的异常。另一件事是,您只是将 0 存储到 valuematrix 长度的地方,startplace 将始终为零(0)。
标签: java android arrays arraylist indexoutofboundsexception