我在 Java 中有三个日期:a、b、c。任何或所有这些日期都可以为空。在没有大量 if-else block 的情况下,确定 a、b、c 中最早日期的最有效方法是什么?
最佳答案
无法绕过 null 检查,但通过一些重构,您可以让它变得轻松。
创建一个安全比较两个日期的方法:
/**
* Safely compare two dates, null being considered "greater" than a Date
* @return the earliest of the two
*/
public static Date least(Date a, Date b) {
return a == null ? b : (b == null ? a : (a.before(b) ? a : b));
}
然后组合调用:
Date earliest = least(least(a, b), c);
实际上,您可以使它成为任何Comparable
的通用方法:
public static <T extends Comparable<T>> T least(T a, T b) {
return a == null ? b : (b == null ? a : (a.compareTo(b) < 0 ? a : b));
}
关于java - 查找3个日期中最早的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15820951/