Reputation: 2695
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.
Upvotes: 2
Views: 2919
Reputation: 718788
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:
equals
and hashCode
methods are returning contradictory answers for the object.equals
or hashCode
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 the remove
method to not find it.)equals
method as an overload, not an override of equals(Object)
. (That could explain why your equals
is not being called ... assuming that your assertion is factually correct.)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.
Upvotes: 0
Reputation: 36456
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.
Upvotes: 0
Reputation: 37007
My guess would be that your object's hashCode()
implementation is returning a different value than when you added the object to the set.
Upvotes: 6