Alex Rivera | Logout

Why equals() method when we have == operator?

Asked 2010-05-05T11:34:53.167
36

When I see the implementation of equals() method it does nothing but same as what == does. So my question is what was the need to have this as separate method when we have == operator which does the same work?

Edit
Report

2 Answers

19

In case of primitives, the == operator checks if two values are the same.
If it aren't primitives, it checks if it are two pointers (or references) pointing to the same instance of an object.

The equals() method performs a custom check, which is in Object checking the reference, by using ==. But in other classes, sometimes equals() is overridden (I don't know if this is a correct past participle). equals() have to check the content.

So, for example:

int i0 = 34;
int i1 = 34;
int i2 = 35;
// results
i0 == i1: true
i1 == i0: true
i2 == i0: false

But if we have non-primitives

String str0 = new String("Hello man!");
String str1 = new String("Hello man!");
String str2 = new String("!nam olleH");
String str2copy = str2;
// Results
str0 == str1: false // Pointer to two different object, so == will give false
str1 == str2: false // Idem
str2 == str2copy: true // So this are two pointers to the same object
str0.equals(str1): true // This are not the same objects, but they are equal
str1 == str1: true // Again: two times a pointer to the same  object

So, why str0.equals(str1) returns true? Because the String class has an override of equals(). And in that method it doesn't check if they are equal by doing return this == obj; But in that method, there is a full check. I don't know which method they use to compare the two strings, but here are two possible ways:

  • Generating from the the two string a hash-code and check if they are equal (int == int)
  • Checking character by character if they are the same.

So I hope this is clear now.

answered 2010-05-05T11:52:38.323
1

That's done so to make this possible:

String s1 = new String("foo");
String s2 = new String("foo");

System.out.println(s1 == s2); // false?! Different references!
System.out.println(s1.equals(s2)); // true

If you check the source of String#equals(), you'll see that it has overridden the Object#equals() appropriately to compare each other's internal character array (the actual value). Many other classes have this method overridden as well.

answered 2010-05-05T11:49:35.533

Your Answer