As I understand, == operator is used for reference comparison, i.e. whether both objects point to the same memory location or not. To test this I created a small java program, but getting not consistent results. Do anyone have any clue on this?
import java.util.HashSet;
import java.util.Set;
public class EqualOperatorTest {
public static void main(String[] args) {
boolean result;
Employee employee1 = new Employee();
employee1.setId(1);
employee1.setName("XYZ");
Employee employee2 = new Employee();
employee2.setId(1);
employee2.setName("XYZ");
result = employee1.equals(employee2);
System.out.println("Comparing two different Objects with equals() method: " + result); //1. This returns True. Ok as we have overridden equals
result = (employee1 == employee2);
System.out.println("Comparing two different Objects with == operator: " + result); //2. This returns False. Why? hashcode of both employee1 and employee2 are same but still == comparison returning false.
//3. Validating hashcode of reference variables employee1 and employee2. We can see both has same hashcode (bcos we have overridden hashcode too in Employee class). But then why above employee1 == employee2 is returning false. Afterall == compares the memory location (or hashcode) and both have the same hashcodes,
System.out.println("employee1 : " + employee1); //employee1 and employee2 has same hashcode
System.out.println("employee2 : " + employee2); //employee1 and employee2 has same hashcode
// Creating hashset and storing the same employee references.
Set empSet = new HashSet();
empSet.add(employee1);
empSet.add(employee2);
System.out.println(empSet); //returns only one memory location(hashcode) as we have overridden hashcode in Employee class. Ok
employee1 = employee2; //Setting employee2 in employee1
result = (employee1 == employee2);
System.out.println("Comparing two reference pointing to same Object with == operator: " + result); //This returns True. Ok
}
}
Need to understand why behavior of == operator is not same at 2 and 3.
My Employee class is simple with two class level variables, their getters and setters and overridden equals and hashcode methods
public class Employee {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}