Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compute the hashCode() from the object's address?

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)?

like image 842
Thomas Avatar asked Sep 24 '08 18:09

Thomas


People also ask

How is hashCode of an object calculated?

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.

Will the hashCode () method of object class return the address of the object?

No, the HashCode() function returns an integer.

How is hashCode calculated in Java?

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 .

Which method is used to get the hashCode of the given object?

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.


2 Answers

Either use System.identityHashCode() or use an IdentityHashMap.

like image 141
Alex Miller Avatar answered Sep 29 '22 22:09

Alex Miller


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().

like image 31
Bill the Lizard Avatar answered Sep 29 '22 23:09

Bill the Lizard