Possible Duplicate:
Difference Between Equals and ==
For example, if I have
MyClass foo = new MyClass();
MyClass bar = new MyClass();
if (foo == bar) {
// do something
}
if (foo < bar) {
// do something
}
if (foo > bar) {
// do something
}
how do foo
and bar
get compared? Does Java look for .compareTo()
methods to be implemented for MyClass
? Does Java compare the actual binary structure of the objects bit for bit in memory?
Very simply the arithmetic comparison operators ==
and !=
compare the object references, or memory addresses of the objects. >
, and <
and related operators can't be used with objects.
So ==
, !=
is useful only if you want to determine whether two different variables point to the same object.
As an example, this is useful in an event handler: if you have one event handler tied to e.g. multiple buttons, you'll need to determine in the handler which button has been pressed. In this case, you can use ==
.
Object comparison of the type that you're asking about is captured using methods like .equals
, or special purpose methods like String.compareTo
.
It's worth noting that the default Object.equals
method is equivalent to ==
: it compares object references; this is covered in the docs. Most classes built into Java override equals
with their own implementation: for example, String
overrides equals
to compare the characters one at a time. To get a more specific/useful implementation of .equals
for your own objects, you'll need to override .equals
with a more specific implementation.
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