Hi, consider the following code: String s = new String("abc"); StringBuffer sb = new StringBuffer("abc"); The expression sb.equals(s) is false, but why is s.equals(sb) false? I know that StringBuffer does not override equals, but String does. So I expected that s.equals(sb) calls the overloaded String method which goes after the contents of sb, not the reference address itself. Any ideas? Thanks, Bernd
The equals method takes an Object as a paramater (because it's defined in the Object class), but, in general, if you call equals on one object type and pass it another object type, it'll always come back as false. It just doesn't make sense for two entirely different types of objects to be "equal." However, had you done this:
Now you'd be comparing a String object with a String object, which makes more sense than comparing a String object with a StringBuffer object. I hope that helps, Corey
It just doesn't make sense for two entirely different types of objects to be "equal." However, had you done this:
Maybe another way to think about it, if it helps to resolve the confusion, is this: Sun had something in particular in mind when they created the 'equals' method. There is a moral contract it is expected to obey. That contract is "only return true if the implementation of the two objects is equivalent". That isn't the same as "only return true if the two objects could be thought of has having equivalent values for some particular purpose". The Sun notion of equals is more stringent, and really better from an OO programming standpoint. It allows you to have a reasonable expectation that you could use X and Y interchangeably in a wide variety of situations, although there are some limitations to that.
Reid - SCJP2 (April 2002)
Joined: Nov 20, 2001
Hello All, thanks for your feedback, this is very helpful for me. -Bernd