Is there a java Set collection which ignores .equals

I'm doing something weird. I want to create a Set, but I want to ignore the equals override on those objects, instead I want to do obj1 == obj2 for the equals comparison (really).

So imagine I have a couple of objects that look like this

public static class BrokenEquals
{
    @Override
    public int hashCode()
    {
        return 1;
    }


    @Override
    public boolean equals(Object obj)
    {
        return true;
    }
}

If I did this

    Set<Object> objs = new HashSet<>();
    objs.add(new BrokenEquals());
    objs.add(new BrokenEquals()); // objs.size() == 1

Obviously the Set will have a size of 1 (because the two objects are "equal"). Instead I want the set to contain the two distinct objects.

However, if I do this

    BrokenEquals obj = new BrokenEquals();
    Set<Object> objs = new HashSet<Object>();
    objs.add(obj);
    objs.add(obj); // objs.size() == 1

I would expect the size of the set to be 1;

I don't have access to change the .equals methods

The reason I want this is that I'm traversing an object graph with cycles. I don't want to be caught in one.

Jon Skeet
people
quotationmark

You could use IdentityHashMap and just ignore the values (the keys will form a set).

There are various implementations of IdentityHashSet available online, too. You could use Guava, for example, with Sets.newIdentityHashSet:

Set<Object> set = Sets.newIdentityHashSet();
objs.add(obj);
objs.add(obj); // Size will be 1

Mind you, I'd try to fix the classes which implement equals in a broken way, too...

people

See more on this question at Stackoverflow