String comparison order in Java
Are both the String comparison methods below considered to be equal
public class TestString {
public static final String CONSTVAL="foo";
public boolean testString1(String testVal) {
return testVal.equalsIgnoreCase(CONSTVAL);
}
public boolean testString2(String testVal) {
return CONSTVAL.equalsIgnoreCase(testVal);
}
}
or should one type开发者_开发技巧 of comparison be favoured over another?
You should call equals on the constant since it avoids the risk of NullPointerException when testVal
is null.
public boolean testString2(String testVal) {
return CONSTVAL.equalsIgnoreCase(testVal);
}
One advantage of the latter is that it won't throw an exception if testVal
is null.
I would expect the results to be the same, other than that.
At first glance I would agree with @Jon Skeet, but then I noticed that CONSTVAL isn't final.
If it was final then testString2() is the safest and best way to test for equality.
When a constant value compare itself to another value you're almost sure to not have null value.
In your case,
new TestString().testString1(null);
will throw an exception, whereas,
new TestString().testString2(null);
wont.
But this kind of notation could be considered as a yoda condition.
精彩评论