Search code examples
javadictionaryhashmapcomparehashcode

How to overwrite the hashcode method that returns a unique hashcode value with its unique entity ID in my defined Java object?


I faced a case of using a complex Map which uses my defined Java object as its key, to do this the class of this object need to implement interface Comparable and overwrite Object's hashcode and equals methods, and I want to use unique ID of object of this class as it hashcode, but the unique ID is Long type and the type of value hashcode returns is Integer, this may suffer from data corruption and inconsistency if ID of object increased to a very large one.

Is there any way to convert a unique long-type ID to a hashcode that can also be used to identify between objects?


Solution

  • The easiest solution would be to rely on java.lang.Long's built-in hashCode():

    @Override
    public int hashCode() {
        return Long.valueOf(getId()).hashCode();
    }
    

    Edit:
    As per the comment below, if the id is stored as a java.lang.Long and not a primitive long, it's even simpler:

    @Override
    public int hashCode() {
        return getId().hashCode();
    }