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???
How does it know that the variables refer to the same object?
Because the values of the variables are the same references. (Your variables are t1
and t2
. The values of those variables are references. Those references are used as a way of navigating to objects, basically.)
Suppose you and I both have pieces of paper with a house's street address on (that's my usual analogy for "variables with references"). How do we check whether they refer to the same house? We see whether the address is the same.
There are some potential twists here, as in some cases the form of the reference may not be the same between two expressions, but that's the basic idea.
(Note that just because I've used "address" in the analogy, that doesn't mean a Java reference is always a memory address. It's "a way of navigating to an object", that's all. It may or may not just be an address.)
From the JVM specification section 2.2:
The Java Virtual Machine contains explicit support for objects. An object is either a dynamically allocated class instance or an array. A reference to an object is considered to have Java Virtual Machine type reference. Values of type reference can be thought of as pointers to objects. More than one reference to an object may exist. Objects are always operated on, passed, and tested via values of type reference.
See more on this question at Stackoverflow