Object t = 4;
Object s = 4;
if (t == s) { // false
}
List<Object> q = new List<object>() { t };
Boolean found = q.Contains(s); // found = true!
In the above code, I am not surprised by t == s
returning false
; it's comparing references to two objects and the references aren't the same.
But I am surprised the the Contains is returning true; obviously it's not just comparing object references..it's like it's comparing the unboxed values of 4 and 4..but how and why does it know to unbox the objects to compare them? I'm trying to understand the bigger pricniple at play here.
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).
== is for value equality. It's used to know if two objects have the same value. is is for reference equality. It's used to know if two references refer (or point) to the same object, i.e if they're identical.
equals() method in Java. Both equals() method and the == operator are used to compare two objects in Java. == is an operator and equals() is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.
equals() method. The major difference between the == operator and . equals() method is that one is an operator, and the other is the method. Both these == operators and equals() are used to compare objects to mark equality.
The expression
q.Contains(s)
is looking for an element of q
for which EqualityComparer<object>.Default
.Equals(element, s)
is true. For boxed primitives, this compares the values.
Contains
, internally, is using the instance object.Equals
method to compare the elements. It is not using the ==
operator.
The Equals
method is virtual, whereas the == operator
is static. This means that the ==
operator will determine which code to run based on the compile time type of the variable (and not the object at run time that the variable holds). A virtual method, on the other hand, is not statically bound. It determines which overload of Equals
to run based on the run time type of the value the variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With