【问题标题】:Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 6 [duplicate]线程“主”java.lang.IndexOutOfBoundsException 中的异常:索引:6,大小:6 [重复]
【发布时间】:2017-10-16 09:35:37
【问题描述】:

这段代码有问题

    List<String> listaTags = new ArrayList<String>();





    int i = 0;
    String current = listaTags.get(i);

    while (listaTags.size() > 1 && listaTags.contains("/".concat(current)) != current.contains("/")) {

        if (current.equals(listaTags.get(i + 1))) {

            listaTags.remove(current);
            listaTags.remove(listaTags.get(i + 1));

            if (i < 0) {
                i++;
            }
        }

        i++;

    }

    System.out.println("errore nel codice");

}

listatags 有六个元素

错误是:

线程“主”java.lang.IndexOutOfBoundsException 中的异常: 索引:6,大小:6

谁能帮帮我?

【问题讨论】:

  • if (i &lt; 0) 语句可以删除 - 我不可能小于零。您的 IndexOutOfBoundsException 可能会在循环中的几个循环后发生 - 值 current 永远不会改变,因此循环将永远继续(您可能希望在 while 循环中包含 String current =
  • 列表中的索引是从零开始的,所以如果列表有 6 个项目,那么有效的索引值是 0 到 5(含); 6 是无效索引。
  • 如果列表有6个元素,那么这些元素的索引是从0到5。元素6不存在

标签: java arraylist


【解决方案1】:

由于列表的大小为 6,因此索引为 0,1,2,3,4,5(本例中为 i 的值)

你总是将 i 的值增加 1,当 i = 5 时,它会抛出 IndexOutOfBoundsException。

你可以做一个修复

if (i < 5 && current.equals(listaTags.get(i + 1))) {...}

【讨论】:

    【解决方案2】:

    这一行

    if (current.equals(listaTags.get(i + 1)))   
    

    抛出异常,因为在 'while' 中,每次列表大小都大于 1 并且您的 i 值达到大于列表大小的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 2017-01-02
      • 2016-01-12
      • 2013-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-04
      相关资源
      最近更新 更多