Last active
August 29, 2015 14:11
-
-
Save raphw/77a2ad467fe16372c274 to your computer and use it in GitHub Desktop.
Manual hash code computation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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