When you override equals() you should also override hashCode(). The reason will be shortly clear.
The following rule must be always true:
When a.equals(b) then a.hashCode() = b.hashCode()
Most collections use equals() to find or remove elements.
The hashCode() is used to insert values into a HashTable, HashMap or HashSet. An hash table uses an hash key to store values internally into a bucket. Each bucket contain might contains a group of values, so at this point equals() is used to find the exact match. This is the reason the two calls work togheter.
Consider that == is different than equals(), because the first compare the references, not their content. However, the default implementation of equals() in the class Object, use the == operator.
It is not true that hashCode provides a unique identifier for an object, but equal objects must have same hash code.
This is an example of a class that overrides the two methods:
public class Person { private int id; private String name; public boolean equals(Object o){ if (o == this) return true; if(!(o instanceof Person)) return false; Person other = (Person) o; if (this.id != other.id) { return false; } if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } return true; } public int hashCode(){ int result = 17; result = 31 * result + this.id; hash = 31 * hash + (this.name != null ? this.name.hashCode() : 0); return result; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
The check for equality is added only for performance:
if (o == this) return true;
In the equals it's not required a null check, because this is automatically managed by instanceof:
if(o == null) return false; // Not required
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.