Please follow the below code,
String s1 = "ABC";
String s2 = new String("ABC");
String s3 = "ABC";
System.out.println(s1.hashCode()); // 64578
System.out.println(s2.hashCode()); // 64578
System.out.println(" s1 == s2 "+(s1 == s2)); // s1 == s2 false
System.out.println(" s1 == s3 "+(s1 == s3)); // s1 == s3 true
Here, both String s1 and s2 have same hashcode and qualify by equals, but fail equality by ==, why ?
Is it because s1 and s2 are different objects though both having the same hashcode and qalify by eqauls, if yes how come, please explain me ?
Also, please look at the below example,
class Employee{
private Integer employeeCode;
Employee(Integer empCode){
this.employeeCode = empCode;
}
@Override
public int hashCode(){
return this.employeeCode * 21;
}
public boolean equals(Object o){
Employee emp = (Employee) o;
return this.employeeCode.equals(emp.employeeCode);
}
}
public class HashCodePractise01{
public static void main(String [] args){
Employee e1 = new Employee(1);
Employee e2 = new Employee(1);
System.out.println(e1.hashCode()); // 21
System.out.println(e2.hashCode()); // 21
System.out.println("e1.equals(e2) "+(e1.equals(e2))); // e1.equals(e2) true
System.out.println("e1 == e2 "+(e1 == e2)); // e1 == e2 false
}
}
In the above example also, both employee objects have same hashcode and qualify equality by .equals method but still they fail equality in ==.
In both the above cases, why are they two different objects ? please explain