从主要包含空值的 Comparables 列表中获取最小值和最大值的最佳方法是什么? [英] What is the best way to get min and max value from a list of Comparables that main contain null values?
本文介绍了从主要包含空值的 Comparables 列表中获取最小值和最大值的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在考虑这样的事情:
I am thinking about something like this:
public static <T extends Comparable<T>> T minOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.first();
}
public static <T extends Comparable<T>> T maxOf(T...ts){
SortedSet<T> set = new TreeSet<T>(Arrays.asList(ts));
return set.last();
}
但不是空安全的,这也是我想要的.
But is not null safe, which is something I want too.
你知道解决这个问题的更好方法吗?
Do you know a better way to solve this problem?
评论后我也试过 min():
After the comments I have also tried min():
public static <T extends Comparable<T>> T minOf(T...ts){
return Collections.min(Arrays.asList(ts), new Comparator<T>(){
public int compare(T o1, T o2) {
if(o1!=null && o2!=null){
return o1.compareTo(o2);
}else if(o1!=null){
return 1;
}else{
return -1;
}
}});
}
你怎么看?
推荐答案
你为什么关心空安全?您确定要在您的集合中允许空值吗?
And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection?
这篇关于从主要包含空值的 Comparables 列表中获取最小值和最大值的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文