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?
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With