How to remove integer from list? [duplicate]

痞子三分冷 提交于 2020-01-13 08:16:10

问题


I need to remove integer from integer arraylist. I have no problem with strings and other objects. But when i removing, integer is treated as an index instead of object.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(300);
list.remove(300);

When I am trying to remove 300 i am getting: 06-11 06:05:48.576: E/AndroidRuntime(856): java.lang.IndexOutOfBoundsException: Invalid index 300, size is 3


回答1:


This is normal, there are two versions of the .remove() method for lists: one which takes an integer as an argument and removes the entry at this index, the other which takes a generic type as an argument (which, at runtime, is an Object) and removes it from the list.

And the lookup mechanism for methods always picks the more specific method first...

You need to:

list.remove(Integer.valueOf(300));

in order to call the correct version of .remove().




回答2:


Use indexof to find the index of the item.

list.remove(list.indexOf(300));



回答3:


Try (passing an Integer, object, instead of an int, primitive) -

list.remove(Integer.valueOf(300));

to invoke the right method - List.remove(Object o)




回答4:


Please try below code to remove integer from list,

public static void main(String[] args) {
        List<Integer> lIntegers = new ArrayList<Integer>();
        lIntegers.add(1);
        lIntegers.add(2);
        lIntegers.add(300);
        lIntegers.remove(new Integer(300));
        System.out.println("TestClass.main()"+lIntegers);
}

If you remove item by passing primitive then it will take it as index and not value/object




回答5:


Use list.remove((Integer)300);


来源:https://stackoverflow.com/questions/17037583/how-to-remove-integer-from-list

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