Martin Sotelo
Martin Sotelo

Reputation: 23

Compare objects which can be null and empty string ("")

Hello I've come to a point where i need a function which compares 2 objects from different sources among other things it also compares strings while form one source iget a null and from the other an empty object string.

my code is

private static boolean areDifferent(Object o1, Object o2) {
    if ("".equals(o1)) {
        o1 = null;
    }
    if ("".equals(o2)) {
        o2 = null;
    }
    if (o1 == null || o2 == null) {
        return !(o1 == o2);
    }
    return !o1.equals(o2);
}

Is there a better way to write this?

Upvotes: 2

Views: 1386

Answers (1)

rolfl
rolfl

Reputation: 17707

You can use a ternary for it (and I would convert null to ""):

return !(o1 == null ? "" : o1).equals(o2 == null ? "" : o2);

Upvotes: 5

Related Questions