【问题标题】:JAVA Collections using iterator and equals vs. ==使用迭代器和等于 vs. == 的 JAVA 集合
【发布时间】:2016-10-30 11:38:07
【问题描述】:

请您解释一下关于代码的以下陈述:

Collection<String> stringCollection = new HashSet<String>();
stringCollection.add(new String ("bye"));
stringCollection.add(new String ("hi"));
stringCollection.add(new String ("bye again"));
for( Iterator<String> iter=stringCollection.iterator();
    iter.hasNext();){
         String str=iter.next();
         if(str.equals("hi"))
             iter.remove();
}
for (String str: stringCollection){
        if(str.equals("hi"))
               stringCollection.remove("hi");
}
System.out.println(stringCollection.size());

如果我们改变两个循环的顺序,那么代码将运行没有错误并打印 2: Wrong 存在运行时错误,但为什么看起来正确?

【问题讨论】:

标签: java collections iterator


【解决方案1】:

该错误是因为您在迭代循环中尝试删除集合中的一项,因此每当在这段代码中调用 remove 方法时都会抛出并发修改异常。

for (String str : stringCollection) {
    if (str.equals("hi"))
        stringCollection.remove("hi");
}

如果您运行发布的代码没有错误的原因是因为第一个循环删除了“hi”项,因此第二个循环永远不会调用 stringCollection.remove(...)。

正如@Tunaki 所提到的,这已经解释了here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-09
    • 2018-04-08
    • 2011-04-25
    • 2013-01-13
    • 2015-08-17
    • 2020-12-18
    相关资源
    最近更新 更多