I am studying Overriding hashCode()
and equals(Object obj)
methods of Object
class.
body of equals(Object obj)
method in Object
class is :
public boolean equals(Object obj) {
return (this == obj);
}
and hashCode()
is native
:
public native int hashCode();
I have a class Test
with overrided equals(Object obj)
and hashCoe()
:
public class Test {
public static void main(String[] args){
Test t1 = new Test();
Test t2 = new Test();
System.out.println("t1 toString() : " + t1.toString());
System.out.println("t1, Hex value of hashcode : " + Integer.toHexString(t1.hashCode()));
System.out.println("t2 toString() : " + t2.toString());
System.out.println("t2, Hex value of hashcode : " + Integer.toHexString(t2.hashCode()));
System.out.println(t1.equals(t2));
}
@Override
public int hashCode() {
return 999; //hard coded value is just for testing
}
@Override
public boolean equals(Object obj) {
return (this == obj);
}
}
Output of my Code is :
t1 toString() : demo.Test@3e7
t1, Hex value of hashcode : 3e7
t2 toString() : demo.Test@3e7
t2, Hex value of hashcode : 3e7
false //why it is false
why equals(Object obj)
returns false
in this case if both objects toString()
returns the same reference ID (hashcode) [I am not sure if it compares hashcode or not].
What does ==
operator actually compare in case of objects?
in this answer, answerer said that ==
that is, it returns true if and only if both variables refer to the same object, if their references are one and the same.
How does it know that the variables refer to the same object???