Brady Zhu
Brady Zhu

Reputation: 1405

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?

Upvotes: 3

Views: 485

Answers (3)

Mureinik
Mureinik

Reputation: 312219

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();
}

Upvotes: 1

thkala
thkala

Reputation: 86433

The most common way that the main Java libraries convert a long to an int for the hashCode() method is with a couple of bitwise operations:

@Override
public int hashCode() {
    return (int)(value ^ (value >>> 32));
}

Incindentally, in Java 8 there is a Long.hashCode(long) static method that does just that:

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

Please note that this process is not reversible - there isn't a one-to-one mapping from long values to their hash code, due to the differing ranges.

Upvotes: 0

Ankit Gupta
Ankit Gupta

Reputation: 2599

you can call hashcode method of Long simply

for example :

new Long(4).hashCode();

Upvotes: 0

Related Questions