Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when you compare two of the same type objects using ==, >, <, etc, in Java? [duplicate]

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?

like image 639
trusktr Avatar asked Dec 04 '22 14:12

trusktr


1 Answers

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.

like image 101
pb2q Avatar answered Jan 07 '23 02:01

pb2q