Skip to content

Instantly share code, notes, and snippets.

@baiyanhuang
Created July 11, 2012 06:32
Show Gist options
  • Save baiyanhuang/3088400 to your computer and use it in GitHub Desktop.
Save baiyanhuang/3088400 to your computer and use it in GitHub Desktop.
generate hashcode based on effective java
package baiyanhuang;
import java.util.Arrays;
/**
*
* A utility class to help generate hash code: This is based on the theory from Effective Java, Item 9
*
*/
public class HashCodeGenerator {
private static final int INIT_VALUE = 17;
private static final int MULTI_COEF = 31;
private int hashCode = INIT_VALUE;
private void updateHashCode(final int value) {
hashCode = hashCode * MULTI_COEF + value;
}
// 1. boolean
public void addField(final boolean field) {
int value = field ? 1 : 0;
updateHashCode(value);
}
// 2. byte, char, short, int
public void addField(final byte field) {
int value = (int) field;
updateHashCode(value);
}
public void addField(final char field) {
int value = (int) field;
updateHashCode(value);
}
public void addField(final short field) {
int value = (int) field;
updateHashCode(value);
}
public void addField(final int field) {
int value = (int) field;
updateHashCode(value);
}
// 3. long - what is the rationale? (exclusive OR of the two halves of the primitive long value )
public void addField(final long field) {
int value = (int) (field ^ (field >>> 32));
updateHashCode(value);
}
// 4. float
public void addField(final float field) {
int value = Float.floatToIntBits(field);
updateHashCode(value);
}
// 5. double
public void addField(final double field) {
long value = Double.doubleToLongBits(field);
addField(value);
}
// 6. object
public void addField(final Object field) {
int value = field == null ? 0 : field.hashCode();
updateHashCode(value);
}
// 7. arrays
public <T> void addField(final T[] field) {
int value = Arrays.hashCode(field);
updateHashCode(value);
}
/**
* return the computed hash code
*/
public int hashCode() {
return hashCode;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment