I have an object in a LinkedHashSet
that implements equals
, hashCode
and compareTo
(in a superclass) but when I try to remove that exact object from the set set.remove(obj)
the remove method returns false
and the object remains in the set. Is the implementation of LinkedHashSet
supposed to call the equals()
method of its objects? Because it doesn't. Could this be a java bug? I'm running 1.6.0_25.
Why isn't my Java LinkedHashSet removing an object it contains?
2.8k Views Asked by mekazu AtThere are 3 best solutions below

LinkedHashSet
works fine for me:
import java.util.*;
public class Test {
public static void main( String[] args ) {
LinkedHashSet<String> lhs = new LinkedHashSet<String>();
String s = "hi";
lhs.add( s );
System.out.println( lhs );
lhs.remove( s );
System.out.println( lhs );
}
}
Perhaps you're passing in a reference to a different object to the remove method? Are you sure you didn't change the reference in any way?
Also make sure that hashCode()
returns the same value when you insert it as when you are trying to remove it.

The chances of this being a bug in LinkedHashSet
are infinitessimnally small. You should dismiss this as a plausible explanation of your problem.
Assuming that this is a bug in your code, then it could be due to a number of things. For instance:
- Your
equals
andhashCode
methods are returning contradictory answers for the object. - Your
equals
orhashCode
methods depend on mutable fields and those fields are being changed while the object is in the set. (For instance, if the hashcode value changes, the object is likely to be on the wrong hash chain, causing theremove
method to not find it.) - You have declared the
equals
method as an overload, not an override ofequals(Object)
. (That could explain why yourequals
is not being called ... assuming that your assertion is factually correct.) - The object you are trying to remove is (in reality) not the one you inserted.
- Something else has already removed the object.
- You are running a different version of some class that does not match the source code you have been examining.
Now, I know that you have dismissed some of these explanations. But that may have been premature. Review the evidence that you based that dismissal on.
Another approach you could use is to use a Java debugger to forensically examine the data structures (e.g. the innards of the LinkedHashSet
) and single-step the code where the deletion is supposed to be happening.
My guess would be that your object's
hashCode()
implementation is returning a different value than when you added the object to the set.