How to compare two lines when both can be null?

I know that it is better to use the equals method with the == operator (see this question ). I want two strings to be compared as equal if they are both zero or the same string. Unfortunately, the equals method will call NPE if the strings are null . My code is:

 boolean equals(String s1, String s2) { if (s1 == null && s2 == null) { return true; } if (s1 == null || s2 == null) { return false; } return s1.equals(s2); } 

It is not elegant. What is the correct way to conduct this test?

+45
java equality equals
May 6 '15 at 3:43
source share
3 answers

If Java is 7+, use Objects.equals() ; its documentation explicitly indicates that:

[...] if both arguments are null, true is returned, and if only one argument is null, false is returned. Otherwise, equality is determined using the equals method of the first argument.

What would you like.

If you do not, your method can be rewritten to:

 return s1 == null ? s2 == null : s1.equals(s2); 

This works because the .equals() contract ensures that for any object o o.equals(null) always false.

+78
May 6 '15 at 15:47
source share

From Objects.equals() :

 return (a == b) || (a != null && a.equals(b)); 

Very simple, self-evident and elegant.

+44
May 6 '15 at 3:47
source share

If you cannot use the Java 7+ solution, but you have Guava or Commons Lang in the classpath, you can use the following:

guavas

 import com.google.common.base.Objects; Objects.equal(s1, s2); 

Commons Lang :

 import org.apache.commons.lang3.builder.EqualsBuilder; new EqualsBuilder().append(s1, s2).isEquals(); 

or

 import org.apache.commons.lang3.StringUtils; StringUtils.equals(s1, s2); 
+4
May 6 '15 at
source share



All Articles