Top Description Fields Constructors Methods
org.apache.commons.lang3.builder

public Class HashCodeBuilder

extends Object
implements Builder<Integer>
Class Inheritance
All Implemented Interfaces
org.apache.commons.lang3.builder.Builder
Imports
java.lang.reflect.AccessibleObject, .Field, .Modifier, java.util.Collection, .Comparator, .HashSet, .Objects, .Set, org.apache.commons.lang3.ArraySorter, .ArrayUtils, .ObjectUtils, .Validate

Assists in implementing 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.

The following is the approach taken. When appending a data field, the current total is multiplied by the multiplier then a relevant value for that data type is added. For example, if the current hashCode is 17, and the multiplier is 37, then appending the integer 45 will create a hash code of 674, namely 17 * 37 + 45.

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 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);
}

The HashCodeExclude annotation can be used to exclude fields from being used by the reflectionHashCode methods.

Since
1.0

Field Summary

Modifier and TypeField and Description
private static final int
DEFAULT_INITIAL_VALUE

The default initial value to use in reflection hash code building.

private static final int
DEFAULT_MULTIPLIER_VALUE

The default multiplier value to use in reflection hash code building.

private final int
iConstant

Constant to use in building the hashCode.

private int
iTotal

Running total of the hashCode.

private static final ThreadLocal<Set<IDKey>>
REGISTRY

A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops.

Constructor Summary

AccessConstructor and Description
public
HashCodeBuilder()

Uses two hard coded choices for the constants needed to build a hashCode.

public
HashCodeBuilder(final int
an odd number used as the initial value
initialOddNumber
,
final int
an odd number used as the multiplier
multiplierOddNumber
)

Two randomly chosen, odd numbers must be passed in. Ideally these should be different for each class, however this is not vital.

Method Summary

Modifier and TypeMethod and Description
public HashCodeBuilder

Returns:

this instance.
append
(final boolean
the boolean to add to the hashCode
value
)

Append a hashCode for a boolean.

public HashCodeBuilder

Returns:

this instance.
append
(final boolean[]
the array to add to the hashCode
array
)

Append a hashCode for a boolean array.

public HashCodeBuilder

Returns:

this instance.
append
(final byte
the byte to add to the hashCode
value
)

Append a hashCode for a byte.

public HashCodeBuilder

Returns:

this instance.
append
(final byte[]
the array to add to the hashCode
array
)

Append a hashCode for a byte array.

public HashCodeBuilder

Returns:

this instance.
append
(final char
the char to add to the hashCode
value
)

Append a hashCode for a char.

public HashCodeBuilder

Returns:

this instance.
append
(final char[]
the array to add to the hashCode
array
)

Append a hashCode for a char array.

public HashCodeBuilder

Returns:

this instance.
append
(final double
the double to add to the hashCode
value
)

Append a hashCode for a double.

public HashCodeBuilder

Returns:

this instance.
append
(final double[]
the array to add to the hashCode
array
)

Append a hashCode for a double array.

public HashCodeBuilder

Returns:

this instance.
append
(final float
the float to add to the hashCode
value
)

Append a hashCode for a float.

public HashCodeBuilder

Returns:

this instance.
append
(final float[]
the array to add to the hashCode
array
)

Append a hashCode for a float array.

public HashCodeBuilder

Returns:

this instance.
append
(final int
the int to add to the hashCode
value
)

Append a hashCode for an int.

public HashCodeBuilder

Returns:

this instance.
append
(final int[]
the array to add to the hashCode
array
)

Append a hashCode for an int array.

public HashCodeBuilder

Returns:

this instance.
append
(final long
the long to add to the hashCode
value
)

Append a hashCode for a long.

public HashCodeBuilder

Returns:

this instance.
append
(final long[]
the array to add to the hashCode
array
)

Append a hashCode for a long array.

public HashCodeBuilder

Returns:

this instance.
append
(final Object
the Object to add to the hashCode
object
)

Append a hashCode for an Object.

public HashCodeBuilder

Returns:

this instance.
append
(final Object[]
the array to add to the hashCode
array
)

Append a hashCode for an Object array.

public HashCodeBuilder

Returns:

this instance.
append
(final short
the short to add to the hashCode
value
)

Append a hashCode for a short.

public HashCodeBuilder

Returns:

this instance.
append
(final short[]
the array to add to the hashCode
array
)

Append a hashCode for a short array.

private void
appendArray(final Object
the array to add to the hashCode
object
)

Append a hashCode for an array.

public HashCodeBuilder

Returns:

this instance.
appendSuper
(final int
the result of calling super.hashCode()
superHashCode
)

Adds the result of super.hashCode() to this builder.

public Integer

Returns:

hashCode based on the fields appended
build
()

Implements org.apache.commons.lang3.builder.Builder.build.

Returns the computed hashCode.

public boolean
equals(final Object obj)

Overrides java.lang.Object.equals.

Implements equals using the hash code.

pack-priv static Set<IDKey>

Returns:

Set the registry of objects being traversed
getRegistry
()

Gets the registry of objects being traversed by the reflection methods in the current thread.

public int

Returns:

hashCode based on the fields appended
hashCode
()

Overrides java.lang.Object.hashCode.

The computed hashCode from toHashCode() is returned due to the likelihood of bugs in mis-calling toHashCode() and the unlikeliness of it mattering what the hashCode for HashCodeBuilder itself is.

pack-priv static boolean

Returns:

boolean true if the registry contains the given object.
isRegistered
(final Object
The object to lookup in the registry.
value
)

Tests whether the registry contains the given object.

private static void
reflectionAppend(final Object
the object to append details of
object
,
final Class<?>
the class to append details of
clazz
,
final HashCodeBuilder
the builder to append to
builder
,
final boolean
whether to use transient fields
useTransients
,
final String[]
Collection of String field names to exclude from use in calculation of hash code
excludeFields
)

Appends the fields and values defined by the given object of the given Class.

public static int

Returns:

int hash code
reflectionHashCode
(final int
a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code
initialNonZeroOddNumber
,
final int
a non-zero, odd number used as the multiplier
multiplierNonZeroOddNumber
,
final Object
the Object to create a hashCode for
object
)

Uses reflection to build a valid hash code from the fields of object.

public static int

Returns:

int hash code
reflectionHashCode
(final int
a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code
initialNonZeroOddNumber
,
final int
a non-zero, odd number used as the multiplier
multiplierNonZeroOddNumber
,
final Object
the Object to create a hashCode for
object
,
final boolean
whether to include transient fields
testTransients
)

Uses reflection to build a valid hash code from the fields of object.

public static <
the type of the object involved
T
>
int

Returns:

int hash code
reflectionHashCode
(final int
a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code
initialNonZeroOddNumber
,
final int
a non-zero, odd number used as the multiplier
multiplierNonZeroOddNumber
,
final T
the Object to create a hashCode for
object
,
final boolean
whether to include transient fields
testTransients
,
final Class<? super T>
the superclass to reflect up to (inclusive), may be null
reflectUpToClass
,
final String...
array of field names to exclude from use in calculation of hash code
excludeFields
)

Uses reflection to build a valid hash code from the fields of object.

public static int

Returns:

int hash code
reflectionHashCode
(final Object
the Object to create a hashCode for
object
,
final boolean
whether to include transient fields
testTransients
)

Uses reflection to build a valid hash code from the fields of object.

public static int

Returns:

int hash code
reflectionHashCode
(final Object
the Object to create a hashCode for
object
,
final Collection<String>
Collection of String field names to exclude from use in calculation of hash code
excludeFields
)

Uses reflection to build a valid hash code from the fields of object.

public static int

Returns:

int hash code
reflectionHashCode
(final Object
the Object to create a hashCode for
object
,
final String...
array of field names to exclude from use in calculation of hash code
excludeFields
)

Uses reflection to build a valid hash code from the fields of object.

private static void
register(final Object
The object to register.
value
)

Registers the given object.

public int

Returns:

hashCode based on the fields appended
toHashCode
()

Returns the computed hashCode.

private static void
unregister(final Object
The object to unregister.
value
)

Unregisters the given object.

Inherited from java.lang.Object:
clonefinalizegetClassnotifynotifyAlltoStringwaitwaitwait

Field Detail

DEFAULT_INITIAL_VALUEback to summary
private static final int DEFAULT_INITIAL_VALUE

The default initial value to use in reflection hash code building.

DEFAULT_MULTIPLIER_VALUEback to summary
private static final int DEFAULT_MULTIPLIER_VALUE

The default multiplier value to use in reflection hash code building.

iConstantback to summary
private final int iConstant

Constant to use in building the hashCode.

iTotalback to summary
private int iTotal

Running total of the hashCode.

REGISTRYback to summary
private static final ThreadLocal<Set<IDKey>> REGISTRY

A registry of objects used by reflection methods to detect cyclical object references and avoid infinite loops.

Since
2.3

Constructor Detail

HashCodeBuilderback to summary
public HashCodeBuilder()

Uses two hard coded choices for the constants needed to build a hashCode.

HashCodeBuilderback to summary
public HashCodeBuilder(final int initialOddNumber, final int multiplierOddNumber)

Two randomly chosen, 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.

Parameters
initialOddNumber:int

an odd number used as the initial value

multiplierOddNumber:int

an odd number used as the multiplier

Exceptions
IllegalArgumentException:
if the number is even

Method Detail

appendback to summary
public HashCodeBuilder append(final boolean value)

Append a hashCode for a boolean.

This adds 1 when true, and 0 when false to the hashCode.

This is in contrast to the standard Boolean#hashCode() handling, which computes a hashCode value of 1231 for Boolean instances that represent true or 1237 for Boolean instances that represent false.

This is in accordance with the Effective Java design.

Parameters
value:boolean

the boolean to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final boolean[] array)

Append a hashCode for a boolean array.

Parameters
array:boolean[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final byte value)

Append a hashCode for a byte.

Parameters
value:byte

the byte to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final byte[] array)

Append a hashCode for a byte array.

Parameters
array:byte[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final char value)

Append a hashCode for a char.

Parameters
value:char

the char to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final char[] array)

Append a hashCode for a char array.

Parameters
array:char[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final double value)

Append a hashCode for a double.

Parameters
value:double

the double to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final double[] array)

Append a hashCode for a double array.

Parameters
array:double[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final float value)

Append a hashCode for a float.

Parameters
value:float

the float to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final float[] array)

Append a hashCode for a float array.

Parameters
array:float[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final int value)

Append a hashCode for an int.

Parameters
value:int

the int to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final int[] array)

Append a hashCode for an int array.

Parameters
array:int[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final long value)

Append a hashCode for a long.

Parameters
value:long

the long to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final long[] array)

Append a hashCode for a long array.

Parameters
array:long[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final Object object)

Append a hashCode for an Object.

Parameters
object:Object

the Object to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final Object[] array)

Append a hashCode for an Object array.

Parameters
array:Object[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final short value)

Append a hashCode for a short.

Parameters
value:short

the short to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendback to summary
public HashCodeBuilder append(final short[] array)

Append a hashCode for a short array.

Parameters
array:short[]

the array to add to the hashCode

Returns:HashCodeBuilder

this instance.

appendArrayback to summary
private void appendArray(final Object object)

Append a hashCode for an array.

Parameters
object:Object

the array to add to the hashCode

appendSuperback to summary
public HashCodeBuilder appendSuper(final int superHashCode)

Adds the result of super.hashCode() to this builder.

Parameters
superHashCode:int

the result of calling super.hashCode()

Returns:HashCodeBuilder

this instance.

Since
2.0
buildback to summary
public Integer build()

Implements org.apache.commons.lang3.builder.Builder.build.

Returns the computed hashCode.

Returns:Integer

hashCode based on the fields appended

Annotations
@Override
Since
3.0
equalsback to summary
public boolean equals(final Object obj)

Overrides java.lang.Object.equals.

Implements equals using the hash code.

Annotations
@Override
Since
3.13.0
getRegistryback to summary
pack-priv static Set<IDKey> getRegistry()

Gets the registry of objects being traversed by the reflection methods in the current thread.

Returns:Set<IDKey>

Set the registry of objects being traversed

Since
2.3
hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

The computed hashCode from toHashCode() is returned due to the likelihood of bugs in mis-calling toHashCode() and the unlikeliness of it mattering what the hashCode for HashCodeBuilder itself is.

Returns:int

hashCode based on the fields appended

Annotations
@Override
Since
2.5
isRegisteredback to summary
pack-priv static boolean isRegistered(final Object value)

Tests whether the registry contains the given object. Used by the reflection methods to avoid infinite loops.

Parameters
value:Object

The object to lookup in the registry.

Returns:boolean

boolean true if the registry contains the given object.

Since
2.3
reflectionAppendback to summary
private static void reflectionAppend(final Object object, final Class<?> clazz, final HashCodeBuilder builder, final boolean useTransients, final String[] excludeFields)

Appends the fields and values defined by the given object of the given Class.

Parameters
object:Object

the object to append details of

clazz:Class<?>

the class to append details of

builder:HashCodeBuilder

the builder to append to

useTransients:boolean

whether to use transient fields

excludeFields:String[]

Collection of String field names to exclude from use in calculation of hash code

reflectionHashCodeback to summary
public static int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final Object object)

Uses reflection to build a valid hash code from the fields of object.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

Transient members will be not be used, as they are likely derived fields, and not part of the value of the Object.

Static fields will not be tested. Superclass fields will be included.

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.

Parameters
initialNonZeroOddNumber:int

a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code

multiplierNonZeroOddNumber:int

a non-zero, odd number used as the multiplier

object:Object

the Object to create a hashCode for

Returns:int

int hash code

Exceptions
NullPointerException:
if the Object is null
IllegalArgumentException:
if the number is zero or even
See Also
HashCodeExclude
reflectionHashCodeback to summary
public static int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final Object object, final boolean testTransients)

Uses reflection to build a valid hash code from the fields of object.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

If the TestTransients parameter is set to true, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the Object.

Static fields will not be tested. Superclass fields will be included.

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.

Parameters
initialNonZeroOddNumber:int

a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code

multiplierNonZeroOddNumber:int

a non-zero, odd number used as the multiplier

object:Object

the Object to create a hashCode for

testTransients:boolean

whether to include transient fields

Returns:int

int hash code

Exceptions
NullPointerException:
if the Object is null
IllegalArgumentException:
if the number is zero or even
See Also
HashCodeExclude
reflectionHashCodeback to summary
public static <T> int reflectionHashCode(final int initialNonZeroOddNumber, final int multiplierNonZeroOddNumber, final T object, final boolean testTransients, final Class<? super T> reflectUpToClass, final String... excludeFields)

Uses reflection to build a valid hash code from the fields of object.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

If the TestTransients parameter is set to true, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the Object.

Static fields will not be included. Superclass fields will be included up to and including the specified superclass. A null superclass is treated as java.lang.Object.

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.

Parameters
<T>
the type of the object involved
initialNonZeroOddNumber:int

a non-zero, odd number used as the initial value. This will be the returned value if no fields are found to include in the hash code

multiplierNonZeroOddNumber:int

a non-zero, odd number used as the multiplier

object:T

the Object to create a hashCode for

testTransients:boolean

whether to include transient fields

reflectUpToClass:Class<? super T>

the superclass to reflect up to (inclusive), may be null

excludeFields:String[]

array of field names to exclude from use in calculation of hash code

Returns:int

int hash code

Exceptions
NullPointerException:
if the Object is null
IllegalArgumentException:
if the number is zero or even
Since
2.0
See Also
HashCodeExclude
reflectionHashCodeback to summary
public static int reflectionHashCode(final Object object, final boolean testTransients)

Uses reflection to build a valid hash code from the fields of object.

This constructor uses two hard coded choices for the constants needed to build a hash code.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

If the TestTransients parameter is set to true, transient members will be tested, otherwise they are ignored, as they are likely derived fields, and not part of the value of the Object.

Static fields will not be tested. Superclass fields will be included. If no fields are found to include in the hash code, the result of this method will be constant.

Parameters
object:Object

the Object to create a hashCode for

testTransients:boolean

whether to include transient fields

Returns:int

int hash code

Exceptions
NullPointerException:
if the object is null
See Also
HashCodeExclude
reflectionHashCodeback to summary
public static int reflectionHashCode(final Object object, final Collection<String> excludeFields)

Uses reflection to build a valid hash code from the fields of object.

This constructor uses two hard coded choices for the constants needed to build a hash code.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

Transient members will be not be used, as they are likely derived fields, and not part of the value of the Object.

Static fields will not be tested. Superclass fields will be included. If no fields are found to include in the hash code, the result of this method will be constant.

Parameters
object:Object

the Object to create a hashCode for

excludeFields:Collection<String>

Collection of String field names to exclude from use in calculation of hash code

Returns:int

int hash code

Exceptions
NullPointerException:
if the object is null
See Also
HashCodeExclude
reflectionHashCodeback to summary
public static int reflectionHashCode(final Object object, final String... excludeFields)

Uses reflection to build a valid hash code from the fields of object.

This constructor uses two hard coded choices for the constants needed to build a hash code.

It uses AccessibleObject.setAccessible to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly.

Transient members will be not be used, as they are likely derived fields, and not part of the value of the Object.

Static fields will not be tested. Superclass fields will be included. If no fields are found to include in the hash code, the result of this method will be constant.

Parameters
object:Object

the Object to create a hashCode for

excludeFields:String[]

array of field names to exclude from use in calculation of hash code

Returns:int

int hash code

Exceptions
NullPointerException:
if the object is null
See Also
HashCodeExclude
registerback to summary
private static void register(final Object value)

Registers the given object. Used by the reflection methods to avoid infinite loops.

Parameters
value:Object

The object to register.

toHashCodeback to summary
public int toHashCode()

Returns the computed hashCode.

Returns:int

hashCode based on the fields appended

unregisterback to summary
private static void unregister(final Object value)

Unregisters the given object.

Used by the reflection methods to avoid infinite loops.

Parameters
value:Object

The object to unregister.

Since
2.3