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 ofi. While List is an indexed collection, soList.remove(i)removes the element at theith 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:
list.remove(0)removes the element at index 0, resulting inNotice 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 isSimilarly the next operation,
list.remove(2)“hops over” the element 0, resulting inAnd last,
list.remove(3)removes the last element, giving the end result: