Question

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.

Was it helpful?

Solution

My guess would be that your object's hashCode() implementation is returning a different value than when you added the object to the set.

OTHER TIPS

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 and hashCode methods are returning contradictory answers for the object.
  • Your 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.)
  • You have declared the 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.)
  • 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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top