
org.solovyev.common.HashCodeBuilder Maven / Gradle / Ivy
/*
* Copyright 2013 serso aka se.solovyev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ---------------------------------------------------------------------
* Contact details
*
* Email: [email protected]
* Site: http://se.solovyev.org
*/
package org.solovyev.common;
import javax.annotation.Nonnull;
/**
*
* Assists in implementing {@link Object#hashCode()} methods.
*
*
*
* This class enables a good hashCode
method to be built for any class. It follows the rules laid out in
* the book Effective Java by Joshua Bloch. Writing a
* good hashCode
method is actually quite difficult. This class aims to simplify the process.
*
*
*
* All relevant fields from the object should be included in the hashCode
method. Derived fields may be
* excluded. In general, any field used in the equals
method must be used in the hashCode
* method.
*
*
*
* To use this class write code as follows:
*
*
*
* public class Person {
* String name;
* int age;
* boolean smoker;
* ...
*
* public int hashCode() {
* // you pick a hard-coded, randomly chosen, non-zero, odd number
* // ideally different for each class
* return new HashCodeBuilder(17, 37).
* append(name).
* append(age).
* append(smoker).
* toHashCode();
* }
* }
*
*
*
* If required, the superclass hashCode()
can be added using {@link #appendSuper}.
*
*
*
* Alternatively, there is a method that uses reflection to determine the fields to test. Because these fields are
* usually private, the method, reflectionHashCode
, uses AccessibleObject.setAccessible
* to change the visibility of the fields. This will fail under a security manager, unless the appropriate permissions
* are set up correctly. It is also slower than testing explicitly.
*
*
*
* A typical invocation for this method would look like:
*
*
*
* public int hashCode() {
* return HashCodeBuilder.reflectionHashCode(this);
* }
*
*
* @author Apache Software Foundation
* @author Gary Gregory
* @author Pete Gieser
* @author Sergey Solovyev
* @version $Id: HashCodeBuilder.java 907376 2010-02-07 03:43:02Z mbenson $
* @since 1.0
*/
public class HashCodeBuilder {
/*
**********************************************************************
*
* FIELDS
*
**********************************************************************
*/
/**
* Constant to use in building the hashCode.
*/
private final int constant;
/**
* Running total of the hashCode.
*/
private int total = 0;
/*
**********************************************************************
*
* CONSTRUCTORS
*
**********************************************************************
*/
/**
*
* Uses two hard coded choices for the constants needed to build a hashCode
.
*
*/
private HashCodeBuilder() {
constant = 37;
total = 17;
}
/**
*
* Two randomly chosen, non-zero, odd numbers must be passed in. Ideally these should be different for each class,
* however this is not vital.
*
*
*
* Prime numbers are preferred, especially for the multiplier.
*
*
* @param initialNonZeroOddNumber a non-zero, odd number used as the initial value
* @param multiplierNonZeroOddNumber a non-zero, odd number used as the multiplier
* @throws IllegalArgumentException if the number is zero or even
*/
private HashCodeBuilder(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) {
if (initialNonZeroOddNumber == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires a non zero initial value");
}
if (initialNonZeroOddNumber % 2 == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires an odd initial value");
}
if (multiplierNonZeroOddNumber == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires a non zero multiplier");
}
if (multiplierNonZeroOddNumber % 2 == 0) {
throw new IllegalArgumentException("HashCodeBuilder requires an odd multiplier");
}
constant = multiplierNonZeroOddNumber;
total = initialNonZeroOddNumber;
}
@Nonnull
public static HashCodeBuilder newInstance() {
return new HashCodeBuilder();
}
@Nonnull
public static HashCodeBuilder newInstance(int initialNonZeroOddNumber, int multiplierNonZeroOddNumber) {
return new HashCodeBuilder(initialNonZeroOddNumber, multiplierNonZeroOddNumber);
}
/*
**********************************************************************
*
* METHODS
*
**********************************************************************
*/
/**
*
* Append a hashCode
for a boolean
.
*
*
* This adds constant * 1
to the hashCode
and not a 1231
or
* 1237
as done in java.lang.Boolean. This is in accordance with the Effective Java
* design.
*
*
* @param value the boolean to add to the hashCode
* @return this
*/
public HashCodeBuilder append(boolean value) {
total = total * constant + (value ? 0 : 1);
return this;
}
/**
*
* Append a hashCode
for a boolean
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(boolean[] array) {
if (array == null) {
total = total * constant;
} else {
for (boolean element : array) {
append(element);
}
}
return this;
}
// -------------------------------------------------------------------------
/**
*
* Append a hashCode
for a byte
.
*
*
* @param value the byte to add to the hashCode
* @return this
*/
public HashCodeBuilder append(byte value) {
total = total * constant + value;
return this;
}
// -------------------------------------------------------------------------
/**
*
* Append a hashCode
for a byte
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(byte[] array) {
if (array == null) {
total = total * constant;
} else {
for (byte element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for a char
.
*
*
* @param value the char to add to the hashCode
* @return this
*/
public HashCodeBuilder append(char value) {
total = total * constant + value;
return this;
}
/**
*
* Append a hashCode
for a char
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(char[] array) {
if (array == null) {
total = total * constant;
} else {
for (char element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for a double
.
*
*
* @param value the double to add to the hashCode
* @return this
*/
public HashCodeBuilder append(double value) {
return append(Double.doubleToLongBits(value));
}
/**
*
* Append a hashCode
for a double
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(double[] array) {
if (array == null) {
total = total * constant;
} else {
for (double element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for a float
.
*
*
* @param value the float to add to the hashCode
* @return this
*/
public HashCodeBuilder append(float value) {
total = total * constant + Float.floatToIntBits(value);
return this;
}
/**
*
* Append a hashCode
for a float
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(float[] array) {
if (array == null) {
total = total * constant;
} else {
for (float element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for an int
.
*
*
* @param value the int to add to the hashCode
* @return this
*/
public HashCodeBuilder append(int value) {
total = total * constant + value;
return this;
}
/**
*
* Append a hashCode
for an int
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(int[] array) {
if (array == null) {
total = total * constant;
} else {
for (int element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for a long
.
*
*
* @param value the long to add to the hashCode
* @return this
*/
// NOTE: This method uses >> and not >>> as Effective Java and
// Long.hashCode do. Ideally we should switch to >>> at
// some stage. There are backwards compat issues, so
// that will have to wait for the time being. cf LANG-342.
public HashCodeBuilder append(long value) {
total = total * constant + ((int) (value ^ (value >> 32)));
return this;
}
/**
*
* Append a hashCode
for a long
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(long[] array) {
if (array == null) {
total = total * constant;
} else {
for (long element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for an Object
.
*
*
* @param object the Object to add to the hashCode
* @return this
*/
public HashCodeBuilder append(Object object) {
if (object == null) {
total = total * constant;
} else {
if (object.getClass().isArray()) {
// 'Switch' on type of array, to dispatch to the correct handler
// This handles multi dimensional arrays
if (object instanceof long[]) {
append((long[]) object);
} else if (object instanceof int[]) {
append((int[]) object);
} else if (object instanceof short[]) {
append((short[]) object);
} else if (object instanceof char[]) {
append((char[]) object);
} else if (object instanceof byte[]) {
append((byte[]) object);
} else if (object instanceof double[]) {
append((double[]) object);
} else if (object instanceof float[]) {
append((float[]) object);
} else if (object instanceof boolean[]) {
append((boolean[]) object);
} else {
// Not an array of primitives
append((Object[]) object);
}
} else {
total = total * constant + object.hashCode();
}
}
return this;
}
/**
*
* Append a hashCode
for an Object
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(Object[] array) {
if (array == null) {
total = total * constant;
} else {
for (Object element : array) {
append(element);
}
}
return this;
}
/**
*
* Append a hashCode
for a short
.
*
*
* @param value the short to add to the hashCode
* @return this
*/
public HashCodeBuilder append(short value) {
total = total * constant + value;
return this;
}
/**
*
* Append a hashCode
for a short
array.
*
*
* @param array the array to add to the hashCode
* @return this
*/
public HashCodeBuilder append(short[] array) {
if (array == null) {
total = total * constant;
} else {
for (short element : array) {
append(element);
}
}
return this;
}
/**
*
* Adds the result of super.hashCode() to this builder.
*
*
* @param superHashCode the result of calling super.hashCode()
* @return this HashCodeBuilder, used to chain calls.
* @since 2.0
*/
public HashCodeBuilder appendSuper(int superHashCode) {
total = total * constant + superHashCode;
return this;
}
/**
*
* Return the computed hashCode
.
*
*
* @return hashCode
based on the fields appended
*/
public int toHashCode() {
return total;
}
/**
*
* The computed hashCode
from toHashCode() is returned due to the likelyhood
* of bugs in mis-calling toHashCode() and the unlikelyness of it mattering what the hashCode for
* HashCodeBuilder itself is.
*
* @return hashCode
based on the fields appended
* @since 2.5
*/
public int hashCode() {
return toHashCode();
}
}