20

I am facing with this unwanted char to int conversion in a loop. Say I have this List of Characters and I want to remove one of those:

List<Character> chars = new ArrayList<>();
chars.add('a');
chars.add('b');
chars.add('c');
chars.remove('a');  // or chars.remove('a'-'0');

so 'a' is interpreted as its int value and I'm getting an IndexOutOfBoundsException exception. Is there any easy workaround for this?

3 Answers 3

27

A char is promoted to an int, which takes precedence over autoboxing, so remove(int) is called instead of remove(Object) you may have intuitively expect.

You can force the "right" method to be called by boxing the argument yourself:

chars.remove(Character.valueOf('a'));
8

You need to cast it to an object type to force the compiler to choose remove(Object) instead of remove(int):

chars.remove((Character) 'a');
6

You can search through the list for where a happens to be.

chars.remove(chars.indexOf('a'));
4
  • No need for that; you just need to call the right overload.
    – SLaks
    Aug 9, 2016 at 22:24
  • Wow I second guessed myself. I initially said to explicitly cast it and then changed my answer. Aug 9, 2016 at 22:26
  • I know, but your initial cast was (I believe) wrong. Casting to the same type has no effect. See my answer.
    – SLaks
    Aug 9, 2016 at 22:26
  • I was wrong anyway. I've voted yours as the right answer either way :). Might as well leave this as another way. Aug 9, 2016 at 22:27

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.