Originally posted by Jayesh Lalwani:
Change this line
to this line
This seems like a poor solution because if either argument is null, the method will return true. In otherwords, null is "equal to" anything.
Another solution is to add more if statements before you access the member field:
Note that you need to check arguments for null before you compare them. This also begs the question "Are two null references really equal? Or *should* they cause an error?" Typically null values are caused by a problem in your code. So doing this check inside the method will silence an error message when there really is a problem. It would be a lot better to check the parameters before you even call the method.
With that said, I have a question about your design: Why does equalTo() take two arguments? Since it is a member method, it already takes an implict argument that refers to the current object. In fact,
Java already provides a mechanism for comparing two Objects with the equals() method. If you override this, your class will be a lot more versatile. It will will also reduce the amount of checks you have to do for null references. For example, you could write a method like this:
You can modify this to check for a null parameter if you want. Notice that only one parameter needs to be checked rather than both.
[ October 09, 2005: Message edited by: Layne Lund ]
[ October 09, 2005: Message edited by: Layne Lund ]