class Employee {
String name;
Employee(String name) {
this.name = name;
}
// hashCode method is not overridden
}
public class HashCodeConfusion {
public static void main(String[] args) {
Employee emp = new Employee("ABC");
Employee emp1 = new Employee("ABC");
if (emp == emp1) {
System.out.println("Employee Same reference");
} else {
System.out.println("Employee Different reference");
}
if (emp.hashCode() == emp1.hashCode()) {
System.out.println("Employee Same hash code");
} else {
System.out.println("Employee Different hash code");
}
// -----------------------------------
String str = new String("ABC");
String str1 = new String("ABC");
if (str == str1) {
System.out.println("String Same reference");
} else {
System.out.println("String Different reference");
}
if (str.hashCode() == str1.hashCode()) {
System.out.println("String Same hash code");
} else {
System.out.println("String Different hash code");
}
}
}
Question/Confusion: The default hashCode for Object class seems to be taking into consideration the object reference and not just the contents, why else would the employee class object with the same name be coming out with a different hash code? If the default implementation of Object class had some hash algorithm based on contents alone, there would not be such a need to override the hashCode method as long as my equals paradigm agrees with the bitwise compatibility.
Anything to clear this confusion?