Wednesday, July 21, 2010

The basics: override hashCode() and equals()

If you want to override equals method in your class, you should also override hashCode method as well. There are a lot of ways the two methods can be implemented incorrectly.

I found the easiest way is to use the wizard in Eclipse, just running Source | Generate hashCode() and equals()... either from menu or context menu. For example, this is what Eclipse generated for a simple class Scrap with a instance variable number:

Correct Implementation Example

The following code exemplifies how all the requirements of equals and hashCode methods should be fulfilled so that the class behaves correctly and consistently with other Java classes. This class implements the equals method in such a way that it only provides equality comparison for the objects of the same class, similar to built-in Java classes like String and other wrapper classes.


package com;

class Test {
private int x;
private String y;
public Test(int x, String y) {

this.x = x;
this.y = y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + x;
result = prime * result + ((y == null) ? 0 : y.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Test)) {
return false;
}
Test other = (Test) obj;
if (x != other.x) {
return false;
}
if (y == null) {
if (other.y != null) {
return false;
}
} else if (!y.equals(other.y)) {
return false;
}
return true;
}



}

public class HashCodeAndEquals {

/**
* @param args
*/
public static void main(String[] args) {


Test t = new Test(10,"rama");
Test t1 = new Test(10,"rama");
System.out.println(t==t1);
System.out.println(t.hashCode()==t1.hashCode());
System.out.println(t.equals(t1));
}
}
-------------------------------------------------------------
The theory (for the language lawyers and the mathematically inclined):

equals() (javadoc) must define an equality relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

public class Person {
private String name;
private int age;
// ...

public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
// if deriving: appendSuper(super.hashCode()).
append(name).
append(age).
toHashCode();
}

public boolean equals(Object obj) {
if (obj == null)
return false;
if (obj == this)
return true;
if (obj.getClass() != getClass())
return false;

Person rhs = (Person) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
append(age, rhs.age).
isEquals();
}
}

Also remember:

When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits

No comments: