I was learning hashcode in more depth and figured that:
1. If you override equals(), you must override hashcode() too.
2. To find if 2 objects are same object, use == operator
Given those 2 factors, in Java I was assuming that when == operator
is used to compare if 2 instances are same or not,
if(object1 == object2)
is actually doing
if(object1.hashcode() == object2.hashcode())
But it appears I was wrong by running the test below.
public class Main {
public static void main(String[] args){
Obj1 one = new Obj1();
Obj1 two = new Obj1();
//is this calling hashCode() in backend???
if(one == two) {
System.out.println("same");
}
else {
System.out.println("nope");
}
//this is of course return true
if(one == one) {
System.out.println("one and one is same");
}
}
}
class Obj1 {
@Override
public int hashCode() {
System.out.println("hashCode() is called");
return 111;
}
@Override
public boolean equals(Object another) {
System.out.println("equals() is called");
return false;
}
}
According to the test which uses == operator
and see if equals()
is called and it wasn't.
So my question is if == operator
can used to compare if the object is same or not, what is the point of overriding equals()
and hashCode()
method for comparison? Isn't == operator
do the job already?
reference:
Overriding hashCode() - is this good enough?
http://mindprod.com/jgloss/hashcode.html
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#equals(java.lang.Object)