Thursday, November 6, 2014

Java - equals vs. ==

Finally, I found an article that explains this in terms that are understandable.

In a previous post, my explanation for C# reference type vs. value type is the difference between your painting ,which is an original masterpiece, getting destroyed (no more painting for anyone) and your painting, which is a print, getting destroyed (more copies can be made).

However, I still had trouble understanding the concept that underlies the issue here of when to use equals method instead of the == operator.

Here's a synopsis of the article:

  1. == compares memory addresses.
  2. equals, as inherited from Object, does, too.
  3. If you want equals to compare data, then you have to override the equals method inherited from Object.
So that explains not only the difference (or similarity, as the case may be) between  == and equals. It also explains that what is being compared is either the address or the data. Hence, in the example in the article, A == C //false because they have different memory addresses. But A.equals(D), once the equals method is overriden, is true because the data is being compared. Thank you, Kurt Mammen!

No comments:

Post a Comment