Class HashKey
This class provides an immutable, thread-safe way to create composite keys from multiple values. It's commonly used for caching scenarios where you need to uniquely identify objects based on multiple configuration parameters or attributes.
Usage Pattern:
Important Notes:
-
All relevant values must be included - When using
HashKeyfor caching, ensure all values that affect the object's identity are included. Missing values can cause different objects to incorrectly share the same cache entry. -
Order matters - The order of arguments in
of(Object...)is significant. Two keys with the same values in different orders will not be equal. -
Immutable - Once created, a
HashKeycannot be modified. This ensures keys remain stable when used in hash-based collections. - Thread-safe - This class is thread-safe and can be safely used as keys in concurrent collections and caches.
-
Null values are supported -
nullvalues can be included in the key and are handled correctly in equality comparisons.
Example:
-
Method Details
-
of
Creates a new hash key from the specified values.The order of arguments is significant - two calls with the same values in the same order will produce equal
HashKeyinstances, while different orders or values will produce different keys.Example:
HashKey
key1 = HashKey.of ("a" ,"b" ,true ); HashKeykey2 = HashKey.of ("a" ,"b" ,true );key1 .equals (key2 );// true HashKeykey3 = HashKey.of ("a" ,"b" ,false );key1 .equals (key3 );// false // Order matters HashKeykey4 = HashKey.of ("b" ,"a" ,true );key1 .equals (key4 );// false (different order) - Parameters:
array- The values that compose this composite key. All values that affect the key's identity should be included.
Can be empty (produces a key representing no values).
Can containnullvalues (handled correctly in equality comparisons).- Returns:
- A new immutable hash key instance.
-
equals
Compares this hash key with another object for equality.Two
HashKeyinstances are considered equal if they contain the same values in the same order. The comparison uses deep equality checking for array elements viaUtils.eq(Object, Object).This method does not perform null or type checking - it assumes the caller has verified the object is a non-null
HashKeyinstance. Passingnullor a non-HashKeyobject will result in aClassCastExceptionorNullPointerException. -
hashCode
Returns the hash code for this hash key.The hash code is computed from all values in the key using
Arrays.deepHashCode(Object[]). This ensures that equal keys have equal hash codes, makingHashKeysuitable for use as keys in hash-based collections likeHashMapandHashSet. Arrays with the same contents (but different references) will produce the same hash code. -
properties
-
toString
-