anonymous anonymous - 1 year ago 66
Java Question

Why ArrayList allowing to add primitive type in the list but not able to remove?

I have some doubt while learning deep about

arraylist
. I can add the primitive type even though Java collections can only store Object References i believe its due to boxing.In the below list but i can't able to remove from the list .

int i = 5;
List<Integer> list = new ArrayList<Integer>();
list.add(i);
System.out.println(list);
list.remove(i); //Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 42, Size: 1
System.out.println("after Remove"+list);


But whenever i use Wrapper its working

Integer i = 5;
List<Integer> list = new ArrayList<Integer>();
list.add(i);
System.out.println(list);
list.remove(i);
System.out.println("after Remove"+list);


I am expecting
remove
method also should be treated like
add
. Please clarify my doubt.

Answer Source

The list.remove method is overloaded, and the two different signatures are used for different purposes. One, list.remove(int), removes an item based on its index, and the other one, list.remove(Object), removes an item based on object equality.

So in the first case the remove method called is - list.remove(int) and the index passed is 5 which does not exist. Hence the exception.

In the second case the call goes to list.remove(Object) and works fine.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download