11

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

Confusion
  • 16,256
  • 8
  • 46
  • 71
Yarh
  • 4,459
  • 5
  • 45
  • 95

5 Answers5

29

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().

fge
  • 119,121
  • 33
  • 254
  • 329
11

Use indexof to find the index of the item.

list.remove(list.indexOf(300));
SBI
  • 2,322
  • 1
  • 17
  • 17
5

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

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

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

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
2

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

Pritesh Shah
  • 857
  • 1
  • 7
  • 8
1
Use list.remove((Integer)300);
Sanjaya Liyanage
  • 4,706
  • 9
  • 36
  • 50