Hash Function for Application Types
Although Java has a default hashCode() method that is inherited by every class, it may be desirable to write a custom hashCode() method for application types:[example from Wikipedia.]
public class Employee{
private int employeeId;
private String firstName;
private String lastName;
private Department dept;
public int hashCode() {
int hash = 1;
hash = hash * 31 + lastName.hashCode();
hash = hash * 29 + firstName.hashCode();
hash = hash * 17 + employeeId;
hash = hash * 13 + (dept == null ? 0
: dept.hashCode());
return hash; } }
This illustrates a good pattern for combining hash codes: multiply one by a prime and add the other. XOR can also be used.