Removing a character from an ArrayList of characters

主宰稳场 提交于 2021-02-04 13:07:14

问题


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?


回答1:


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



回答2:


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



回答3:


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

chars.remove(chars.indexOf('a'));


来源:https://stackoverflow.com/questions/38861354/removing-a-character-from-an-arraylist-of-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!