Skip to content

Instantly share code, notes, and snippets.

@raphw
Last active August 29, 2015 14:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphw/77a2ad467fe16372c274 to your computer and use it in GitHub Desktop.
Save raphw/77a2ad467fe16372c274 to your computer and use it in GitHub Desktop.
Manual hash code computation
class HashCode {
public static void main(String[] args) {
Object object = new Object();
printHash(object.hashCode());
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
long hashCode = 0;
for (long index = 7; index > 0; index--) { // First byte is not part of the hash code
hashCode |= (unsafe.getByte(object, index) & 0x00FF) << ((index - 1) * 8);
}
printHash(hashCode); // hashCode == object.hashCode();
}
private static void printHash(int value) {
System.out.println("HashCode: " + value + " (0x" + Integer.toHexString(value) + ")");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment