I want to hear opinions and arguments on this topic, I’m pretty undecided.
The equals method is the best one for value equality/testing?
if ("text".equals(testString))
Advertisement
Answer
1 and 4 may cause an NPE
since myString
may be null.
Number 3 could also throw an NPE because the expected return is an integer meaning, less than, greater than, or equal too. If the passed argument is null, there would be no basis to return any of those as it would be misleading and any one would be a good as the other. So the best option would be to throw an NPE
.
For number 2, the equals test is a binary test so it is either equal or not.
“test” is used as a reference to equals, so using it will not throw an NPE. In that case, the argument to the equals is myString
. A good equals implementation will first check if the argument is null before using it. Therefore, no NPE
will be thrown.