Reputation: 25
What does the JVM check in object equality (==
)? Is it the hashCode
of two objects or something else?
Upvotes: 0
Views: 340
Reputation: 32980
It is easy to see how JVM treats ==
at bytecode level.
For example
public boolean compare(Object o1, Object o2)
{
return o1 == o2;
}
compiles to the following byte code instructions (use javap -c
to generate this):
public boolean compare(java.lang.Object, java.lang.Object);
Code:
0: aload_1
1: aload_2
2: if_acmpne 7
5: iconst_1
6: ireturn
7: iconst_0
8: ireturn
aload1
and aload2
load the references of o1 and o2 on the stack.
The ==
operation is performed by if_acmpne
.
if_acmpne pops the top two object references off the stack and compares them. If the two object references are not equal (i.e. if they refer to different objects), execution branches to .... If the object references refer to the same object, execution continues at the next instruction.
Of course this doesn't tell you how the JVM interpreter implements object references, or how a bytecode to native compiler like Hotspot implements it, but its a good start to explore the topic.
Upvotes: 0
Reputation: 6515
The equality operator (==
) test for reference equality not hashCode
public static void main(String[] args) {
MyClass obj1=new MyClass();
MyClass obj2=new MyClass(); //obj1 and obj2 refers two different location
System.out.println("obj1= "+obj1+"\tobj2="+obj2);
if(obj1==obj2){ // so return false.
System.out.println("obj1==obj2");
}else{
System.out.println("obj1!=obj2");
}
System.out.println(obj1.hashCode()+"\t"+obj2.hashCode());
}
class MyClass{}
output:
obj1= com.think.test.MyClass@1e9cb75 obj2=com.think.test.MyClass@2c84d9
obj1!=obj2
hashCode
obj1=32099189 obj2=2917593
EDIT
class EqualityTest {
@Override
public int hashCode(){
return 1;
}
public static void main(String... arg){
EqualityTest t1 = new EqualityTest();
EqualityTest t2 =t1; // t2 referring to t1.
System.out.println(t1);
System.out.println(t2);
System.out.println(t1.hashCode());
System.out.println(t2.hashCode());
System.out.println(t1==t2); // so it return true.
}
}
output:
com.think.test.Test9@1
com.think.test.Test9@1
1
1
true
Upvotes: 0
Reputation: 1500215
The ==
operator only checks reference equality. It doesn't call any methods on the object... it just checks whether the two references involved are equal, i.e. they refer to the same object.
In simple cases I believe this is just a matter of comparing the references in a bitwise fashion - checking whether or not they consist of the same bytes. For more complex environments (e.g. "compressed oops") there could be slightly more work involved, in order to compare different representations. But the internally reference is effectively a pointer of some kind, and it's just a matter of comparing the two pointers.
Upvotes: 3
Reputation: 172408
The == is used to compare object references. It simply checks if the two object are pointing to the same reference.
Upvotes: 0