【发布时间】: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 存在运行时错误,但为什么看起来正确?
【问题讨论】:
-
这里提出了 3 个非常不同的问题。你能专注于一个人吗?也就是说,请参阅stackoverflow.com/questions/223918/… for a) 和 stackoverflow.com/questions/14150628/string-constant-pool-java for b) 和 stackoverflow.com/questions/16079931/… for c)
-
Tunaki:一个问题:在这个特定的代码中发生了什么,顺序很重要,
equal?
标签: java collections iterator