When and why does the method boolean java.util.List.remove(Object object)
return false?
The documentation states
[The method ret
from this doc
Removes the first occurrence of the specified element from this list, if it is present (optional operation). If this list does not contain the element, it is unchanged. More formally, removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists). Returns true if this list contained the specified element (or equivalently, if this list changed as a result of the call).
If the Object
passed in is not actually in the list, it wouldn't take any effect on the list and therefore return false.
Edit (thanks Jai):
The method uses the specific Object
s equals()
method to determine if it contains that object. So, if you have custom objects make sure you override the equals() method, and also the hashCode() (to maintain the general contract between the methods).
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