When and why does the method boolean java.util.List.remove(Object object) return false?
The documentation states
[The method ret
Since List is an interface, it wouldn't have a concrete implementation for an example. But taking from ArrayList, it will return false if:
From ArrayList.java
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;
}
Adding the code of fastRemove, for completeness:
private void fastRemove(int index) {
modCount++;
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
}
Proving it:
public static void main(String[] args) {
ArrayList l = new ArrayList();
System.out.println("Removing null on empty list: " + l.remove(null));
System.out.println("Removing an object that won't be found: " + l.remove(new Object()));
}
Result:
Removing null on empty list: false
Removing an object that won't be found: false