【问题标题】:IndexOutOfBoundsException not thrown on adding element at invalid index in Java ArrayList在 Java ArrayList 中的无效索引处添加元素时未引发 IndexOutOfBoundsException
【发布时间】:2013-07-31 11:24:09
【问题描述】:

如果我们阅读添加函数here 的 ArrayList 文档,显然在无效索引处添加元素会引发 IndexOutOfBoundsException。但是为什么下面的代码没有抛出任何异常呢?

public static void main(String args[]){
        List cities = new ArrayList();
        cities.add("Atlanta");
        cities.add("Boston");

        try {
            for (int i = 10000000; i < cities.size(); i++){
                try {
                    cities.add(i, "+");
                } catch (Exception e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                System.out.println(cities.size());
            }
        } catch (Exception e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

        System.out.println(cities);

    }

输出:

[Atlanta, Boston]

Process finished with exit code 0

我目前正在使用 jdk 7 并在 intellij idea 上运行。

【问题讨论】:

  • 因为除了前 2 个元素之外,您没有将任何元素添加到列表中,这些元素会在最后打印出来。
  • for (int i = 0; i
  • “我目前正在使用 jdk 7 并在 intellij idea 上运行。” IntelliJ IDEA 内置了一个很棒的调试器,能够逐步遍历代码-步。这几乎就像它是为解决这样的问题而设计的......

标签: java arraylist indexoutofboundsexception


【解决方案1】:

永远不会进入您的 for 循环,因为 1000000 > city.size()(即 2)。

您的代码完全错误。

【讨论】:

  • 啊我错了!!谢谢!
【解决方案2】:

如果 i 的值从 10000000 开始,并且与 2 (cities.size()) 进行比较,它永远不会更小。

【讨论】:

    【解决方案3】:

    三件事:

    1. 您的循环从i= 10000000cities.size()= 2 开始,因此永远不会满足条件i&lt;2 并且永远不会进入循环。

    2. try{ }catch (Exception e) { e.printStackTrace(); }

    永远不要这样做。尝试捕获特定异常并利用它们! e.printStackTrace() 基本上只是将您的异常转储到输出流上并丢失。

    3。 System.out.println(cities);

    这将使用 ArrayList 的默认 toString() 实现。在这种情况下,它将是[Atlanta, Boston]

    【讨论】:

      猜你喜欢
      • 2014-06-10
      • 2013-06-13
      • 2019-12-17
      • 2012-04-29
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多