Sunday, February 17, 2008

The Issue with Equals Method

We all know that Equals method is synonymous with ==
So we can say
a.b.c.equals(obj) instead of a.b.c == obj
But we may run across some issues here
Lets say there is a chance that a.b can be null
So we can write the code as
If(a.b != null && a.b.c.Equals(obj))
This looks alright but what if a.b.c is null!!
So we can say:
If(a.b != null && a.b.c != null && a.b.c.Equals(obj)
Wait…………..
There is another simple way to write this!
If(a.b != null && a.b.c == obj)
This works even if a.b.c is null
So this means use Equals method only when you’ve overridden the method, in all other cases we can be happy with ==

No comments: