equals() and contains() seemingly contradict

            for(Context context : contexts) {

                if(context.equals(c)){
                    System.out.println(context.equals(c)+" : "+contexts.contains(c));
                }
            }

contexts is a standard java TreeSet

To me, it seems that if this produces ANY output, it should produce “true : true”. Strangely, it always comes back with “true : false”.

Looking at the documentation; I am in essence replicating exactly what the .contains function does, yet getting a different result.

Can anyone explain this?

EDIT: From the java documentation (Collection):

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

It seems likely that the hashcode implementation does not jibe with equals.

The contains method will find where the object should be using the hashcode. It will then check to see if it is there using equals.

I would suggest therefore that if you are getting true:false then you need to fix your hashcode implementation so that

If equals returns true for two objects then hashcode on the two objects return the same value.

With a TreeSet the place where the object should be is located using compareTo so do the equivalent there.