我现在正在阅读 Joshua Bloch 的“Effective Java”,当我阅读第 41 条“明智地使用重载”时,我因为那里使用的示例而感到困惑。我在电脑上试了一下,它确实做到了书中的作用。但我不明白为什么!
这是这个例子:
public class SetList {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<Integer>();
List<Integer> list = new ArrayList<Integer>();
for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}
for (int i = 0; i < 3; i++) {
set.remove(i);
list.remove(i);
}
System.out.println(set + " " + list);
}
}
它输出:
[-3, -2, -1] [-2, 0, 2]
我知道这个例子中的 list.remove() 应该按索引删除,但事实并非如此!列表填满值后,它是:[-3, -2, -1, 0, 1, 2]。因此,当我们删除 0、1 和 2 个元素时,我们应该保留 [0, 1, 2] 而不是 [-2, 0, 2]。那里发生了什么事?