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:
equals()
?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)?
Simply put, hashCode() returns an integer value, generated by a hashing algorithm. Objects that are equal (according to their equals()) must return the same hash code. Different objects do not need to return different hash codes.
No, the HashCode() function returns an integer.
hashcode() is computed via jvm argument -XX:hashCode=N where N can be a number from [0-5]... Depending on an application you may see unexpected performance hits when .
To get this hashcode value for an object, we can use the hashcode() method in Java. It is the means hashcode() method that returns the integer hashcode value of the given object. Since this method is defined in the Object class, hence it is inherited by user-defined classes also.
Either use System.identityHashCode() or use an IdentityHashMap.
System.identityHashCode()
returns the same hash code for the given object as would be returned by the default method hashCode()
, whether or not the given object's class overrides hashCode()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With