The List
interface contains two remove()
methods - remove(Object)
and remove(int)
.
The implementation of remove(Object)
in Java 6 is as follows:
public boolean remove(Object o) {
if (o == null) {
for (int index = 0; index < size; index++)
if (elementData[index] == null) {
fastRemove(index);
return true;
}
} else {
for (int index = 0; index < size; index++)
if (o.equals(elementData[index])) {
fastRemove(index);
return true;
}
}
return false;
}
The implementation of remove(int)
in Java 6 is:
public E remove(int index) {
RangeCheck(index);
modCount++;
E oldValue = (E) elementData[index];
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
In your first example, you're actually calling the remove(int)
method, which removes the object at the specified index. In this case, you specified index 2, which is actually the value "3".
In your second example, you're calling the remove(Object)
method, since there isn't a remove(long)
method and a long
won't be converted into an int
. Based on the implementation of the remove(Object)
method, it looks for object equality. Since your list contains objects of type Integer
and you're providing a Long
, nothing will match it.
The following method is probably a better example of what's happening:
public static void main(String[] args) {
ArrayList<Integer> list;
System.out.println("Removing intNum");
int intNum = 2;
list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
System.out.println("List = " + list);
list.remove(intNum);
System.out.println("List = " + list);
System.out.println("Removing longNum");
long longNum = 2;
list = new ArrayList<Integer>();
list.add(1);
list.add(2);
list.add(3);
System.out.println("List = " + list);
list.remove(longNum);
System.out.println("List = " + list);
}
The output of this code is:
Removing intNum
List = [1, 2, 3]
List = [1, 2]
Removing longNum
List = [1, 2, 3]
List = [1, 2, 3]