public class Hashcode extends Object
Object.hashCode() of a class.
The aim of this class, paired with the class Equals, is to avoid the boilerplate code
needed to implement the Object.hashCode() method and to provide an implementation
that is consistent with the related Object.equals(Object) method.
Even if most of the IDEs provide tools to generate implementations of Object.hashCode()
and Object.equals(Object), the generated code is ugly and hard to understand.
By using this utility class the resulting Object.hashCode() method will be small,
clean and easy to read.
You may have seen a lot of times implementation of the method Object.hashCode()
in this form:
public boolean hashCode()
{
int hashCode = 31
hashCode *= field1 & 0xFFFFF800
hashCode = hashCode ^ (field2 << 11);
hashCode += field3 << 6;
hashCode += field4 == null 0 : field4.hashCode();
return hashCode ^ (hashCode >>> 32);
}
It is quite hard to understand and definitely ugly!
With this utility you can get the same result with a single instruction:
public boolean hashCode()
{
return Hashcode.of( field1, field2, field3, field4 );
}
This class can be used also to get the hash code of a generic object. The values returned by this class will be the same between multiple runs of the Java Virtual Machine.
For example the hash code of an object of type enum
may change between different runs of the JVM
so enum.hashCode() may change while Hashcode.of(enum) will not.
For example you may need to store a complex object and be able to
find it using a unique key. Such key may be based on several fields.
Using this utility you can easily build an hash key that will be the
same across different JVMs and different servers and therefore
can be stored.
| Modifier and Type | Method and Description |
|---|---|
static int |
of(Object object)
Creates an hash code based on the given object.
|
static int |
of(Object object,
Object... others)
Creates an hash code based on the given base object
and an arbitrary long series of other objects.
|
public static int of(Object object)
The hash code for null is 0.
If the given object is an array the hash code is based on its elements.
object - an object to use to compute the hash code.public static int of(Object object, Object... others)
It creates an hash code that is combination of the provided objects.
If all objects are null the hash code is 0.
If one or more of the given objects is an array the hash code is based on its elements.
object - an object to use to compute the hash code.others - other objects to combine with the first one.Copyright © 2011–2020 Nerd4j. All rights reserved.