0

I am new to java. It seems really simple but I can't understand why this is happening.

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);
}

When they print themselves, set prints [-3, -2, -1](desired output) whereas list prints [-2, 0, 2](Not desired output). For list.remove() method, since it is overloading it considers its argument as index, not object. Is this right? Why is this happening and how do I fix list to print desired output using function binding?

Thanks in advance.

Andy
  • 19
  • 3

2 Answers2

1

Set.remove(Object) removes the element that is equals to the Object param while List.remove(int index) removes the elements at the index parameter.

Note that remove(int index); is defined in the List but not in Set interface as the Set interface doesn't have a specific order for elements.

The compiler chooses the method that matches the more with the declared type of the argument. And for a List, remove(int index); is which one that matches more to an int.
Concerning the Set.remove() invocation, the compiler bounds the method to Set.remove(Object) because that is the single possibility and that the boxing feature allows to convert a int to an Integer at compile time.

So as said by Aomine, what you are looking for is :

list.remove((Integer) i) 

Because in this case for the compiler the two methods are eligible but it chooses remove(Object obj); as it is more specific than remove(int index); for an Integer declared type parameter passed.

davidxxx
  • 125,838
  • 23
  • 214
  • 215
0

This is because List provides two flavours of remove()

1) remove(Object)

2) remove(index)

When int is passed to remove the second one is called.

Solution;

list.remove(new Integer(i))

Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25