【问题标题】:Index Out Of Bounds Exception: Invalid index 0, size is 0 [duplicate]索引越界异常:索引 0 无效,大小为 0 [重复]
【发布时间】: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 循环没有被执行,所以placesget(0) 没有添加任何内容。
  • 错误中明确提到 valuesMatrix 的大小为零,因此当您尝试获取其他元素时,它会引发相同的异常。另一件事是,您只是将 0 存储到 valuematrix 长度的地方,startplace 将始终为零(0)。

标签: java android arrays arraylist indexoutofboundsexception


【解决方案1】:

如果valuesMatrix 为空,则places 的长度为0,内部没有值,因此当您尝试执行places.get(0) 时会出错。

【讨论】:

    【解决方案2】:

    1) 请尝试记录您的 valuematrix 长度,因为错误中明确提到 valuesMatrix 大小为零,因此您的 palces 列表也是空的。因此,当您尝试获取第 0 个元素时,它会引发相同的异常。

    2) 另一件事是,您只是将 0 存储到位置列表中的 valuematrix 长度,因此,startplace 的值将始终为零(0)。

    【讨论】:

      【解决方案3】:

      valuesMatrix 的长度肯定是 0,它被分配给 totalPlaces。 因此,您的“for”循环不会运行,并且不会将任何内容添加到您的 ArrayList 'places'。 因此,当您尝试从第零位获取价值时,您会遇到异常。 检查 places 变量的大小,如果大于零,则仅继续执行以下语句:

      for(int i=0; i<totalPlaces; i++){
              places.add(i);
          }
      if (places.size() > 0) {
      int startPlace = places.get(0);
      }
      

      【讨论】:

      • 这是有道理的,但不幸的是我仍然遇到同样的错误..
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-28
      • 2021-07-12
      • 2021-07-13
      • 2013-07-29
      • 1970-01-01
      相关资源
      最近更新 更多