Skip to content

Instantly share code, notes, and snippets.

@deckerego
Created December 6, 2013 14:25
Show Gist options
  • Save deckerego/7825531 to your computer and use it in GitHub Desktop.
Save deckerego/7825531 to your computer and use it in GitHub Desktop.
Several hashcode implementations (including the one within the Java foundation classes) relies on integer overflows to have predictable behavior. This assumption prevents these hashcode implementations from being portable, since integer overflows result in different values across runtime environments. The following hashcode implementation does n…
@Override
public int hashCode() {
int hash = 0, buffer = 0;
int modulo, logicalShiftLeft;
for(int index = 0, max = this.stringProperty.length(); index < max; ++index) {
modulo = index % 4;
logicalShiftLeft = 8 * modulo;
buffer += this.stringProperty.charAt(index) << logicalShiftLeft;
if(modulo == 3) {
hash ^= buffer;
buffer = 0;
}
}
return hash ^ buffer;
}
function hashCode(value) {
var hash = 0, buffer = 0;
var modulo, logicalShiftLeft;
for(var index = 0, max = value.length; index < max; ++index) {
modulo = index % 4;
logicalShiftLeft = 8 * modulo;
buffer += value.charCodeAt(index) << logicalShiftLeft;
if(modulo == 3) {
hash ^= buffer;
buffer = 0;
}
}
return hash ^ buffer;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment