1

Suppose I have:

public class A {
    @Override
    public int hashCode() {
        // some expensive calculation
    }

    @Override
    public boolean equals(Object obj) {
        // some expensive calculation
    }
}

And at some point in my code I wish to have a map with A as the key type using Object's hashCode() and equals() implementations (i.e. two keys of type A will be considered equal if and only if they refer to the same object).

What's the best way to do it?

Ofer
  • 293
  • 3
  • 9

1 Answers1

2

You can override methods upon instantiation

A a = new A(){
  @Override
  public int hashCode() {
    return System.identityHashCode(this);
  }
};

Or use an IdentityHashMap which uses System.identityHashCode

Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77