Mik*_*ike 1 java collections list set
我有以下程序,我在其中添加少量数字来设置和列表然后删除它们,有人可以解释为什么Set和list有不同的行为.
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);
}
Run Code Online (Sandbox Code Playgroud)
}
和输出是
[-3, -2, -1] [-2, 0, 2]
Run Code Online (Sandbox Code Playgroud)
我能够理解Set的行为但无法理解List输出的行为.所有帮助真的很感激.
Set和List是不同类型的集合.组是一个关联集,从而Set.remove(i)将删除具有该元素值的i.List是一个索引集合,因此List.remove(i)删除列表中i第th个位置的元素.
因此,在从包含-3 ... 3的元素的Set中删除元素0到3之后,您的Set将可预测地包含值-3到-1.
使用List,相同删除序列的结果可能会更令人惊讶,但它实际上是合乎逻辑的.最初您的清单包含:
Index 0 1 2 3 4 5 6
Value -3 -2 -1 0 1 2 3
Run Code Online (Sandbox Code Playgroud)
list.remove(0) 删除索引0处的元素,导致
Index 0 1 2 3 4 5
Value -2 -1 0 1 2 3
Run Code Online (Sandbox Code Playgroud)
请注意,(删除)之后的所有元素都向前移动了一个位置!因此,当list.remove(1)在索引1处移除元素时,它会"跳过"元素-2.结果是
Index 0 1 2 3 4
Value -2 0 1 2 3
Run Code Online (Sandbox Code Playgroud)
类似地,下一个操作list.remove(2)"跳过"元素0,导致
Index 0 1 2 3
Value -2 0 2 3
Run Code Online (Sandbox Code Playgroud)
最后,list.remove(3)删除最后一个元素,给出最终结果:
Index 0 1 2
Value -2 0 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |