In Java, I have a subclass Vertex
of the Java3D class Point3f
. Now Point3f
computes equals()
based on the values of its coordinates, but for my Vertex
class I want to be stricter: two vertices are only equal if they are the same object. So far, so good:
class Vertex extends Point3f {
// ...
public boolean equals(Object other) {
return this == other;
}
}
I know this violates the contract of equals()
, but since I'll only compare vertices to other vertices this is not a problem.
Now, to be able to put vertices into a HashMap
, the hashCode()
method must return results consistent with equals()
. It currently does that, but probably bases its return value on the fields of the Point3f
, and therefore will give hash collisions for different Vertex
objects with the same coordinates.
Therefore I would like to base the hashCode()
on the object's address, instead of computing it from the Vertex
's fields. I know that the Object
class does this, but I cannot call its hashCode()
method because Point3f
overrides it.
So, actually my question is twofold:
- Should I even want such a shallow
equals()
? - If yes, then, how do I get the object's address to compute the hash code from?
Edit: I just thought of something... I could generate a random int
value on object creation, and use that for the hash code. Is that a good idea? Why (not)?