[英]Unable to understand the behavior of following program ( Using java collection)
I have following program in which I am adding few number to set and list and then removing them, Could some one please explain why Set and list have different behavior. 我有以下程序,其中我要添加一些数字以设置和列出然后删除它们,请问有人可以解释为什么设置和列表有不同的行为。
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);
}
} }
and output is 和输出是
[-3, -2, -1] [-2, 0, 2]
I am able to understand the behavior of Set but unable to understand the behavior of List output. 我能够理解Set的行为,但无法理解List输出的行为。 All help really appreciated.
所有帮助真的很感激。
Set and List are different types of collections . Set和List是不同类型的集合 。 Set is an associative collection, thus
Set.remove(i)
will remove the element having the value of i
. Set是一个关联集合,因此
Set.remove(i)
将删除具有i
值的元素。 While List is an indexed collection, so List.remove(i)
removes the element at the i
th position in the list. 尽管List是一个索引集合,所以
List.remove(i)
删除列表中第i
个位置的元素。
So after removing the elements 0 to 3 from a Set containing elements of -3 ... 3, your Set will predictably contain the values -3 to -1. 因此,从包含-3 ... 3元素的Set中删除元素0到3后,您的Set可以预测地包含值-3到-1。
With the List, the outcome of the same sequence of removals may be a bit more surprising, but it is actually logical. 对于列表,相同删除顺序的结果可能会有些令人惊讶,但这实际上是合乎逻辑的。 Originally your list contains:
最初,您的列表包含:
Index 0 1 2 3 4 5 6
Value -3 -2 -1 0 1 2 3
list.remove(0)
removes the element at index 0, resulting in list.remove(0)
删除索引为0的元素,导致
Index 0 1 2 3 4 5
Value -2 -1 0 1 2 3
Notice that all elements after the (removed) first have shifted one position forward! 请注意,(删除)之后的所有元素首先都向前移动了一个位置! Thus, when
list.remove(1)
removes the element at index 1, it "hops over" the element -2. 因此,当
list.remove(1)
删除索引1处的元素时,它将“跳过”元素-2。 The result is 结果是
Index 0 1 2 3 4
Value -2 0 1 2 3
Similarly the next operation, list.remove(2)
"hops over" the element 0, resulting in 类似地,下一个操作
list.remove(2)
“跳过”元素0,导致
Index 0 1 2 3
Value -2 0 2 3
And last, list.remove(3)
removes the last element, giving the end result: 最后,
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.