-3

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

Rahul Shivsharan
  • 2,481
  • 7
  • 40
  • 59
  • 1
    Because '==' checks if they are equal in terms of location in memory. They are different memory-wise but by implementing hashcode and equals you said you want them to be equal in a semantic way. – SklogW Sep 06 '15 at 11:04

2 Answers2

4

Two Objects in Java will only ever evaluate to == if they share the same memory location (i.e. if they are literally the SAME object).

In your first example, S1 and S3 are equal because string are immutable, and, so, those literals can be smartly converted to a single cached string by java at compile-time (I think this happens at compile-time, could be runtime. I'm a bit fuzzy on java specifics, feel free to provide an edit if anyone knows for certain).

Bilesh Ganguly
  • 3,792
  • 3
  • 36
  • 58
CollinD
  • 7,304
  • 2
  • 22
  • 45
0

For comparing 2 Strings, you have to use .equals() and not == because .equals() compare the value of Strings while == compare 2 objects(which will not be true anyhow).

burglarhobbit
  • 1,860
  • 2
  • 17
  • 32