LAST UPDATE: MARCH 6, 2015
http://www.javapractices.com/topic/TopicAction.do?Id=17
Please note that many IDEs offer generators for both equals() and hashCode():
The Eclipse IDE.
package org.bjornkrols.templates;
/**
* @author Bjorn Krols (Botre)
* @version 0.0
* @since March 6, 2015
*/
public final class EqualsAndHashCodeTemplate {
public boolean significantBoolean;
public int significantInteger;
private EqualsAndHashCodeTemplate() {
// This class should never be instantiated.
// Do not delete or make accessible.
}
@Override
public int hashCode() {
// Create an int "result" and assign a non-zero value.
int result = 17;
// Create an int "prime" and assign a prime value.
int prime = 34;
/*
For every field tested in the equals-Method, calculate a hash code c by:
If the field f is a boolean: calculate (f ? 0 : 1);
If the field f is a byte, char, short or int: calculate (int)f;
If the field f is a long: calculate (int)(f ^ (f >>> 32));
If the field f is a float: calculate Float.floatToIntBits(f);
If the field f is a double: calculate Double.doubleToLongBits(f) and handle the return value like every long value;
If the field f is an object: Use the result of the hashCode() method or 0 if f == null;
If the field f is an array: See every field as separate element and calculate the hash value in a recursive fashion and combine the values as described next.
Combine the hash value c with result with: result = prime * result + c
*/
result = prime * result + (significantBoolean ? 0 : 1);
result = prime * result + significantInteger;
return result;
}
@Override
public boolean equals(Object object) {
// Optimization for true object equality.
if (object == this) {
return true;
}
// Check if object is an instance of this class (returns false if object is null).
if (!(object instanceof EqualsAndHashCodeTemplate)) {
return false;
}
// Cast object for comparison (safe).
EqualsAndHashCodeTemplate castedObject = (EqualsAndHashCodeTemplate) object;
// Check if all significant fields are equal.
if (castedObject.significantBoolean != this.significantBoolean) {
return false;
}
if (castedObject.significantInteger != this.significantInteger) {
return false;
}
return true;
}
}