return 给定索引 i 的子列表中的项目数,如果有的话,否则为 0;

return number of items in a sub-list at given index i, if any, else 0;

With my workin gout i get IndexOutOfBoundsException: Index -1 out of bounds for length 1

public static int getSize (ArrayList<ArrayList<Integer>> list, int i) {
    if(list == null || list.size() == 0 ) {
        return 0;
    }
    if (!list.get(i).isEmpty()) 
        return list.get(i).size();
    return 0;
}

如果您传递给函数的数组的索引为零,它将抛出该错误。 0 是第一项,因为没有第一项,所以会抛出该错误。

您会注意到它可能会在 for 循环中抛出该错误。我会设置一个断点和 运行 调试器来查看调用此函数时列表的值。

如果您传入一个 空列表 作为第一个参数和 0 作为第二个参数,您将得到您所说的错误: IndexOutOfBoundsException:索引 0 超出长度 0 的范围。也许你正处于这种情况?这是抛出相同异常的 Junit 测试:

  @Test
  public void getSizeTest() {
    getSize(new ArrayList<>(), 0);
  }

  public static int getSize (ArrayList<ArrayList<Integer>> list, int i) {
    for(int j = 0; j < list.get(i).size(); j++) {
      if(!(list.get(i).get(j).equals(0))) {
      }
      return(list.get(i).size());
    }
    return 0;
  }

要获取子列表中的项目数,请执行以下操作。这确保所有值都有效并且 returns 0 或子列表的大小。

public static int getSize (ArrayList<ArrayList<Integer>> list, int i) { 
   if (list != null && !list.isEmpty() && i < list.size() && i >= 0) {
         if (list.get(i) != null) {
             return list.get(i).size();
         }
   }
   return 0;  
}

您可以取消对您确定永远不会发生的情况的任何检查。