import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Scratch {
public static void main(String[] args) {
Set<Date> dates = new HashSet<>();
dates.add(new Date(100));
dates.add(new Date(200));
for (Date date : dates) {
System.out.println("Initial "+date.getTime()+":"+date.hashCode());
date.setTime(date.getTime()+42);
System.out.println("Mutated "+date.getTime()+":"+date.hashCode()+"\n");
}
System.out.println("Size before remove iteration: "+dates.size());
Iterator<Date> iterator = dates.iterator();
while (iterator.hasNext()) {
Date date = iterator.next();
System.out.println("In loop: "+date.getTime()+":"+date.hashCode());
iterator.remove();
}
System.out.println("Size after remove iteration: "+dates.size());
}
}
在 HashSet 内部更改对象后,Java 8 拒绝使用迭代器将其删除,请在删除循环之后检查大小。
Java 8 输出:
Initial 100:100
Mutated 142:142
Initial 200:200
Mutated 242:242
Size before remove iteration: 2
In loop: 142:142
In loop: 242:242
Size after remove iteration: 2
Java 9及以上版本的输出与上述相同,但有以下不同:
Size after remove iteration: 0
为什么会发生这种情况?
HashMap
中默认哈希桶数量这样微不足道的事情也可能会导致问题。 - chrylis -cautiouslyoptimistic-