// 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);
}
Tuesday, 1 February 2011
Implementing null-safe compareTo
Labels:
compareTo(),
Comparison,
java
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment