Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a character from an ArrayList of characters

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?

like image 316
Yar Avatar asked Aug 09 '16 22:08

Yar


3 Answers

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'));
like image 56
Mureinik Avatar answered Oct 17 '22 06:10

Mureinik


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');
like image 20
SLaks Avatar answered Oct 17 '22 06:10

SLaks


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

chars.remove(chars.indexOf('a'));
like image 6
learner0000 Avatar answered Oct 17 '22 05:10

learner0000