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. All help really appreciated.
Set and List are different types of collections . Set is an associative collection, thus Set.remove(i)
will remove the element having the value of i
. While List is an indexed collection, so List.remove(i)
removes the element at the i
th position in the list.
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.
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
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. 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
Index 0 1 2 3
Value -2 0 2 3
And last, list.remove(3)
removes the last element, giving the end result:
Index 0 1 2
Value -2 0 2
调用Set.remove(int)时,java会将参数自动装箱为Integer,但是存在一个List.remove(int),该列表按其索引删除值。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.