本文介绍如何为 `movie` 类实现 `comparable` 接口,使其按 `type` 优先、`id` 次之的顺序自然排序,并正确处理 `null` 值(默认排在末尾)。
在 Java 中,若需让对象支持自然排序(例如用于 Collections.sort() 或 TreeSet),需实现 Comparable 接口并重写 compareTo() 方法。针对 Movie 类的排序需求——先按 type 升序,type 相同时再按 id 升序,且所有 null 值视为最大(即排在末尾)——我们需谨慎处理空值,避免 NullPointerException。
以下是推荐的 compareTo 实现(使用 Java 7+ 的 Objects.compare() 和 Comparator.nullsLast() 风格逻辑,但完全基于原生 API,无需额外依赖):
@Override
public int compareTo(final Movie other) {
// Step 1: 处理 type 比较(null 视为更大)
if (this.type == null && other.type == null) {
// both null → equal on type
} else if (this.type == null) {
return 1; // this null > other non-null → this comes after
} else if (other.type == null) {
return -1; // other null → this comes before
} else {
int typeCmp = this.type.compareTo(other.type);
if (typeCmp != 0) return typeCmp;
}
// Step 2: 处理 id 比较(null 视为更大)
if (this.id == null && other.id == null) {
return 0;
} else if (this.id == null) {
return 1;
} else if (other.id == null) {
return -1;
} else {
return this.id.compareTo(other.id);
}
}
✅ 优势说明:
- 完全自主实现,不依赖第三方库(如 Apache Commons 或 Guava),兼容 JDK 6+;
- 显式、可读性强,每个 null 分支语义清晰;
- 符合“null 更大”的业务要求(即 null 总是排在非 null 之后);
- 时间复杂度 O(1),无副作用。
⚠️ 注意事项: