Here's a nice pitfall I just encountered. Consider a list of integers:
List<Integer> list = new ArrayList<Integer>();
list.add(5);
list.add(6);
list.add(7);
list.add(1);
Any educated guess on what happens when you execute list.remove(1)
? What about list.remove(new Integer(1))
? This can cause some nasty bugs.
What is the proper way to differentiate between remove(int index)
, which removes an element from given index and remove(Object o)
, which removes an element by reference, when dealing with lists of integers?
The main point to consider here is the one @Nikita mentioned - exact parameter matching takes precedence over auto-boxing.
Simply I did like following as suggested by #decitrig in accepted answer first comment.
This helped me. Thanks again #decitrig for your comment. It may help for some one.
list.remove(4)
is an exact match oflist.remove(int index)
, so it will be called. If you want to calllist.remove(Object)
do the following:list.remove((Integer)4)
.Java always calls the method that best suits your argument. Auto boxing and implicit upcasting is only performed if there's no method which can be called without casting / auto boxing.
The List interface specifies two remove methods (please note the naming of the arguments):
remove(Object o)
remove(int index)
That means that
list.remove(1)
removes the object at position 1 andremove(new Integer(1))
removes the first occurrence of the specified element from this list.I don't know about 'proper' way, but the way you suggested works just fine:
removes element at given position and
removes given object from the list.
It's because VM at first attempts to find method declared with exactly the same parameter type and only then tries autoboxing.
Note that even if the VM did not do the right thing, which it does, you could still ensure proper behaviour by using the fact that
remove(java.lang.Object)
operates on arbitrary objects:Simple Java Code Explanation for visualizing difference between
ArrayList.remove(Object o)
andArrayList.remove(int index)
CODE :
OUTPUT :
EXPLAINATION :
CASE 1: We are removing first occurring Integer object with data 7.
CASE 2: Then we are again doing same thing as in
CASE 1
from remaining data.CASE 3: We are removing data at index position 1.
CONCLUSION :
Taking an example of
ArrayList<Integer>
as used in above java code:ArrayList.remove(Integer object)
will simply remove the specific Integer object occurring first in theArrayList
. However,ArrayList.remove(int index)
will always remove the array element at given index position.MORE ABOUT :
We cannot declare
ArrayList<int>
because itint
is primary data-type. Any Class which has the base-classObject
is only specified in theArrayList
generic datatype. eg:ArrayList<String>
,ArrayList<Integer>
etc.