What is the contract between hashcode() and equals() method?

There are following relationship between hashcode() and equals() method in Java.

  • If two object are equal by equals() method then compulsory their hashcode must be equal.
  • If hashcode of two object are equal then we can not tell about equals() method.it may be return true or false.
  • If two object are not equal by equals() method then there are no restriction on hashcode.they may be equal or not.
  • If hashcode of two object is not equal then these two object are not always equal by equals() method.
				
					public class Employee {

	String name;
	int age;

	public boolean equals(Object obj) {
		if (!(obj instanceof Employee)) {
			return false;
		}
		Employee e = (Employee) obj;
		if (name.equals(e.name) && age == e.age) {
			return true;
		} else {
			return false;
		}
	}

	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

}