4

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?

Community
  • 1
  • 1
trusktr
  • 44,284
  • 53
  • 191
  • 263
  • 3
    No, it looks to see if they occupy the same place in memory. That's all. That's why you're supposed to use `equal` to compare objects. – Paul Tomblin Oct 05 '12 at 22:33
  • 1
    See also: http://stackoverflow.com/questions/971954/difference-between-equals-and – assylias Oct 05 '12 at 22:34
  • 1
    @assylias: C# supports operator overloading. Java does not. – Eric Oct 05 '12 at 22:37
  • 2
    @Eric The answer I linked to addresses Java and C# at the same time - which could be confusing. Here is a better link: http://stackoverflow.com/questions/2772763/why-equals-method-when-we-have-operator – assylias Oct 05 '12 at 22:38
  • @trusktr - I edited your question to be less of a duplicate. Please let me know if you approve, and feel free to roll back. – Richard JP Le Guen Oct 05 '12 at 22:57
  • 1
    @RichardJPLeGuen I saw the edit, and rolled back but then applied some of your changes. The thing is, I wasn't knowledgeable enough to ask the question in the same way that you did, so someone without your knowledge (keywords, phrasing, etc) might not be able to find the question using simpler terminology. – trusktr Oct 05 '12 at 23:03
  • @trusktr - np. Just glad the question won't be closed... hopefully. – Richard JP Le Guen Oct 05 '12 at 23:03
  • @RichardJPLeGuen I hope it doesn't. I think it's a good question for beginners, and although similar to http://stackoverflow.com/questions/2772763/, the terminology is sufficiently different that it will attract searchers thinking in different ways. And unlike http://stackoverflow.com/questions/971954/, this one talks specifically about Java. – trusktr Oct 05 '12 at 23:06

5 Answers5

8

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.

pb2q
  • 58,613
  • 19
  • 146
  • 147
  • So what does `.equals()` compare? Does it look to see if both objects have the same methods and properties and whether the properties are also equal? Or does it just check if the properties are equal? Or does it compare them bit to bit? – trusktr Oct 05 '12 at 22:50
  • 1
    @trusktr the _default_ `.equals` method is equivalent to `==`: it compares references. Good followup question: I'll add to answer – pb2q Oct 05 '12 at 22:52
  • Look at the implementation of .equals in string. it's a good start. typically, you first check for reference equality (==), then assignment compatibility (usually with the instanceof operator), and then finally, object specific data comparison. In the case of string, it's the underlying character data. – Matt Oct 06 '12 at 02:21
4

You didn't try it yourself, apparently, because <, >, <= and >= do not work on Objects.

However, == compares the left and right operand. When they are binary the same, it results in true. In the case of objects, in compares the pointers. So which means that this will only result in true if the Object is left and right the very same object in memory.

Other methods, like compareTo and equals are made to provide a custom method of comparing to different objects in memory, but which might be equal to each other (i.e. the data is the same).

In case of Strings, for example:

String str0 = new String("foo");
String str1 = new String("foo");

// A human being would say that the two strings are equal, which is true
// But it are TWO different objects in memory. So, using == will result
// in false

System.out.println(str0 == str1); // false

// But if we want to check the content of the string, we can use the equals method,
// because that method compares character by character of the two objects

String.out.println(str0.equals(str1)); // true
String.out.println(str1.equals(str0)); // true
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • You're right, i didn't try < or >, but in my case I'm only comparing for equality. Thanks for that info. – trusktr Oct 05 '12 at 22:57
2

No it doesn't. It compares whether the two variables are references to the same objects.

Unless you're dealing with types which are subject to autoboxing, such as Integer, you can't use > and < with objects at all.

In the case where you are using an autoboxed type, java doesn't look for specific methods, but will auto-unbox the variables, turning them into primitives - but this isn't the case for the equals operator. The == operator will always compare objects as references, even when comparing autoboxed objects:

    Integer i1 = new Integer(10);
    Integer i2 = new Integer(10);

    if(i1 < i2) { // evaluates to false!
        System.out.println("i1 is less than i2");
    }
    else if(i1 > i2) { // evaluates to false!
        System.out.println("i1 is greater than i2");
    }
    else if(i1 == i2) { // evaluates to false!
        System.out.println("i1 and i2 are equal");
    }
    else {
        System.out.println("Um... well that's just confusingi");
    }
Richard JP Le Guen
  • 28,364
  • 7
  • 89
  • 119
1

It compares the reference value and will only return true if foo and bar point to the same object.

RobEarl
  • 7,862
  • 6
  • 35
  • 50
1

In Java, "==" compares the object identity. "new" is guaranteed to return a new object identity each time.

I'd actually love if "==" would call compareTo. Alas, it doesn't.

nes1983
  • 15,209
  • 4
  • 44
  • 64
  • I wouldn't love it. It would be a huge pain in the ass... How would you ever check if two variables point to the same place in memory, which means that it is only one single object. – Martijn Courteaux Oct 05 '12 at 22:40
  • @MartijnCourteaux Maybe something like `if (x.is(y))` where `.is()` would be inherited from `Object` for all objects. I would prefer if `x==y` used `compareTo` to return `true` or `false`. – trusktr Oct 05 '12 at 22:47
  • I believe Groovy (and maybe ActionScript) uses `==` for equality and `===` to compare references. – Steve Kuo Oct 06 '12 at 03:07
  • @MartijnCourteaux Using reflection, of course. It's a reflective property, after all. – nes1983 Oct 06 '12 at 21:18