Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two objects in Java with possible null values

Tags:

java

People also ask

Can we compare object with null in Java?

Use c == null , since you're comparing references, not objects. Show activity on this post. The equals method (usually) expects an argument of type customer, and may be calling some methods on the object. If that object is null you will get the NullPointerException.

Can you use == for null in Java?

== and !=The comparison and not equal to operators are allowed with null in Java. This can made useful in checking of null with objects in java.

Can you use compareTo with null?

Note that null is not an instance of any class, and e. compareTo(null) should throw a NullPointerException even though e. equals(null) returns false. It is strongly recommended (though not required) that natural orderings be consistent with equals.

How do you compare null in Java?

Use "==" to check a variable's value. A "==" is used to check that the two values on either side are equal. If you set a variable to null with "=" then checking that the variable is equal to null would return true. variableName == null; You can also use "!=


Since Java 7 you can use the static method java.util.Objects.equals(Object, Object) to perform equals checks on two objects without caring about them being null.

If both objects are null it will return true, if one is null and another isn't it will return false. Otherwise it will return the result of calling equals on the first object with the second as argument.


This is what Java internal code uses (on other compare methods):

public static boolean compare(String str1, String str2) {
    return (str1 == null ? str2 == null : str1.equals(str2));
}

For these cases it would be better to use Apache Commons StringUtils#equals, it already handles null strings. Code sample:

public boolean compare(String s1, String s2) {
    return StringUtils.equals(s1, s2);
}

If you dont want to add the library, just copy the source code of the StringUtils#equals method and apply it when you need it.


For those on android, who can't use API 19's Objects.equals(str1, str2), there is this:

android.text.TextUtils.equals(str1, str2);

It is null safe. It rarely has to use the more expensive string.equals() method because identical strings on android almost always compare true with the "==" operand thanks to Android's String Pooling, and length checks are a fast way to filter out most mismatches.

Source Code:

/**
 * Returns true if a and b are equal, including if they are both null.
 * <p><i>Note: In platform versions 1.1 and earlier, this method only worked  well if
 * both the arguments were instances of String.</i></p>
 * @param a first CharSequence to check
 * @param b second CharSequence to check
 * @return true if a and b are equal
 */
public static boolean equals(CharSequence a, CharSequence b) {
    if (a == b) return true;
    int length;
    if (a != null && b != null && (length = a.length()) == b.length()) {
        if (a instanceof String && b instanceof String) {
            return a.equals(b);
        } else {
            for (int i = 0; i < length; i++) {
                if (a.charAt(i) != b.charAt(i)) return false;
            }
            return true;
        }
    }
    return false;
}

Since version 3.5 Apache Commons StringUtils has the following methods:

static int  compare(String str1, String str2)
static int  compare(String str1, String str2, boolean nullIsLess)
static int  compareIgnoreCase(String str1, String str2)
static int  compareIgnoreCase(String str1, String str2, boolean nullIsLess)

These provide null safe String comparison.


Using Java 8:

private static Comparator<String> nullSafeStringComparator = Comparator
        .nullsFirst(String::compareToIgnoreCase); 

private static Comparator<Metadata> metadataComparator = Comparator
        .comparing(Metadata::getName, nullSafeStringComparator)
        .thenComparing(Metadata::getValue, nullSafeStringComparator);

public int compareTo(Metadata that) {
    return metadataComparator.compare(this, that);
}

Compare two string using equals(-,-) and equalsIgnoreCase(-,-) method of Apache Commons StringUtils class.

StringUtils.equals(-, -) :

StringUtils.equals(null, null)   = true
StringUtils.equals(null, "abc")  = false
StringUtils.equals("abc", null)  = false
StringUtils.equals("abc", "abc") = true
StringUtils.equals("abc", "ABC") = false

StringUtils.equalsIgnoreCase(-, -) :

StringUtils.equalsIgnoreCase(null, null)   = true
StringUtils.equalsIgnoreCase(null, "abc")  = false
StringUtils.equalsIgnoreCase("xyz", null)  = false
StringUtils.equalsIgnoreCase("xyz", "xyz") = true
StringUtils.equalsIgnoreCase("xyz", "XYZ") = true