I'm confused regarding the following code...
String str1 = new String("hello");
String str2 = new String("hello");
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
str1.equals(str2) evaluate to true
obj1.equals(obj2) evaluate to false?
I know that the four objects all distinct, so why are string objects treated differently? Am I missing something here?
Thanks a lot
So, when you write "hello" again, you get a reference to the same String object you had last time.
you should still use "equals()" to find two identical Strings, because Strings created at runtime might not be shared like that.
Have you overridden the equals() method in MyClass? If you haven't overridden it, then it will use the default implementation from java.lang.Object which reads something like this:So it only returns true if the two objects compared are references to the same object. You have to override it correctly to work in MyClass; in fact any class you plan to use in "real life" rather than an exercise ought to have an overridden equals() method, and an overridden hashCode method. See the API for java.lang.Object for more details.
See Object.equals()'s documentation for details.
If you have more questions, let 'em fly.
There's no magic or specialness about String that's relevant here; you can override equals() in any of your classes to behave the same way. Whereas the "==" operator is always supposed to mean "is the same object", the equals() method is more usefullly used to mean "is equivalent to".
Originally posted by Campbell Ritchie:
You ought to include a test for other != null in the equals method. If you get as far as trying to test equality against a null object, then you want to return false and exit the method PDQ before you get a NullPointerException!
Not really. getClass().isInstance(other) will return false if other is null.
I tend to write my equals methods a bit differently:
Now most people will use "!getClass().isInstance(o)" or something similar, but that can violate the rule that equals should be symmetric.
Consider this example:
Clearly this violates the rule. By checking that both classes have the exact same class this rule will not be violated.