Tuesday 1 February 2011

Implementing null-safe compareTo

// primarily by name, secondarily by value; null-safe; case-insensitive
public int compareTo(final Metadata other) {
int result = nullSafeStringComparator(this.name, other.name);
if (result != 0) {
return result;
}

return nullSafeStringComparator(this.value, other.value);
}

public static int nullSafeStringComparator(final String one, final String two) {
if (one == null ^ two == null) {
return (one == null) ? -1 : 1;
}

if (one == null && two == null) {
return 0;
}

return one.compareToIgnoreCase(two);
}

No comments:

Post a Comment