![](/img/trans.png)
[英]AWT: I am trying to learn Java and was unable to understand the following program
[英]Unable to understand the behavior of following program ( Using java collection)
我有以下程序,其中我要添加一些数字以设置和列出然后删除它们,请问有人可以解释为什么设置和列表有不同的行为。
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]
我能够理解Set的行为,但无法理解List输出的行为。 所有帮助真的很感激。
Set和List是不同类型的集合 。 Set是一个关联集合,因此Set.remove(i)
将删除具有i
值的元素。 尽管List是一个索引集合,所以List.remove(i)
删除列表中第i
个位置的元素。
因此,从包含-3 ... 3元素的Set中删除元素0到3后,您的Set可以预测地包含值-3到-1。
对于列表,相同删除顺序的结果可能会有些令人惊讶,但这实际上是合乎逻辑的。 最初,您的列表包含:
Index 0 1 2 3 4 5 6
Value -3 -2 -1 0 1 2 3
list.remove(0)
删除索引为0的元素,导致
Index 0 1 2 3 4 5
Value -2 -1 0 1 2 3
请注意,(删除)之后的所有元素首先都向前移动了一个位置! 因此,当list.remove(1)
删除索引1处的元素时,它将“跳过”元素-2。 结果是
Index 0 1 2 3 4
Value -2 0 1 2 3
类似地,下一个操作list.remove(2)
“跳过”元素0,导致
Index 0 1 2 3
Value -2 0 2 3
最后, list.remove(3)
删除最后一个元素,得到最终结果:
Index 0 1 2
Value -2 0 2
调用Set.remove(int)时,java会将参数自动装箱为Integer,但是存在一个List.remove(int),该列表按其索引删除值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.