Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why no autoboxing when removing primitive type from a List in Java?

I have the code below throwing IndexOutOfBoundsException:

 List<Character> list = new ArrayList<>();
 char c  = 'a';
 list.add(c);
 list.remove(c); // gets fixed by passing list.remove((Character)c);

I know that this happens because autoboxing is not happening while removal and it happens while adding an element. My question is why? What is so special in adding that autoboxing from char to Character is possible while in the remove method it's not?

like image 429
Ayushi Jain Avatar asked Dec 04 '22 20:12

Ayushi Jain


1 Answers

That's not really a problem of auto unboxing, but a problem of overloading: there is a List::remove(int) (remove by index in the list) method that exist which is more specific than List::remove(E) (remove by searching an object using Object::equals).

In your case, your char is casted to int.

In the case of add, the equivalent version to removing with an index, is List::add(int, E) (see javadoc for details). List::add(E) is equivalent to list.add(add(list.size(), E).

like image 160
NoDataFound Avatar answered Feb 11 '23 23:02

NoDataFound