I have a very large Set of Immutable Objects so I am thinking of assigning a unique hashcode to them at construction time.
private static int counter = Integer.MIN_VALUE;
private final double foo;
private final double bar;
private final int hashCode;
public MyImmutableObject(double foo, double bar)
{
counter++;
this.foo = foo;
this.bar = bar;
this.hashCode = counter;
}
@Override
public int hashCode()
{
return this.hashCode;
}
/**
* Unneeded override of equals since its the same as in
* Object, but shown for demonstration purposes.
*/
@Override
public boolean equals(final Object obj)
{
return this == obj;
}
This way, I can achieve the highest possible dispersity of keys, since I will have 232 unique keys. Of course, this also means that no two objects of this type will ever be equal, since an object will only be equal to itself.
edit: The Objects are also used as keys in Maps.
Is this possible to do? Are there hidden traps I missed?
Thread safety, for one thing? You could use
AtomicIntegerto get round that, of course.Then there’s also the pointlessness of it, really. The built-in hash code is going to be pretty close to unique without you doing any extra work (and taking an extra 4 bytes per object). Given that you’re not changing the meaning of equality (it’s still basically reference equality) I can’t see that there’s any good reason to do this.