How do I overwrite the hashcode method that returns a unique hashcode value with its unique object id in my specific Java object?
, Java , . Object hashcode equals , , hashcode, - , hashcode Integer, , ID . , -, ?
.
- java.lang.Long
hashCode()
:
@Override
public int hashCode() {
return Long.valueOf(getId()).hashCode();
}
:
, java.lang.Long
, long
, :
@Override
public int hashCode() {
return getId().hashCode();
}
hashcode Long
:
(4).hashCode();
The most common way the core Java libraries convert long
to int
for a method hashCode()
is with multiple bitwise operations:
@Override
public int hashCode() {
return (int)(value ^ (value >>> 32));
}
There is often a Long.hashCode(long)
static method in Java 8 that does just that:
@Override
public int hashCode() {
return Long.hashCode(value);
}
Note that this process is not reversible - there is no one-to-one value between the hash codes long
due to the different ranges.