对列表进行排序< Number> [英] Sorting a List<Number>
本文介绍了对列表进行排序< Number>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何排序列表< Number>
?
示例: / p>
Example:
List<Number> li = new ArrayList<Number>(); //list of numbers
li.add(new Integer(20));
li.add(new Double(12.2));
li.add(new Float(1.2));
推荐答案
Collections.sort(li,new Comparator<Number>() {
@Override
public int compare(Number o1, Number o2) {
Double d1 = (o1 == null) ? Double.POSITIVE_INFINITY : o1.doubleValue();
Double d2 = (o2 == null) ? Double.POSITIVE_INFINITY : o2.doubleValue();
return d1.compareTo(d2);
}
});
请查看 Andreas_D's answer 说明。在上述代码中所有空值和+无穷大值被处理,使得它们移动到结束。
Have a look at Andreas_D's answer for explanation.In the above code all null values and +Infinity values are handled such that they move to the end.
更新1:
jarnbjo 和 aioobe 指出上述实现中的缺陷。我认为最好限制Number的实现。
As jarnbjo and aioobe points out a flaw in the above implementation.So I thought it's better to restrict the implementation's of Number.
Collections.sort(li, new Comparator<Number>() {
HashSet<Class<? extends Number>> allowedTypes;
{
allowedTypes = new HashSet<Class<? extends Number>>();
allowedTypes.add(Integer.class);
allowedTypes.add(Double.class);
allowedTypes.add(Float.class);
allowedTypes.add(Short.class);
allowedTypes.add(Byte.class);
}
@Override
public int compare(Number o1, Number o2) {
Double d1 = (o1 == null) ? Double.POSITIVE_INFINITY : o1.doubleValue();
Double d2 = (o2 == null) ? Double.POSITIVE_INFINITY : o2.doubleValue();
if (o1 != null && o2 != null) {
if (!(allowedTypes.contains(o1.getClass()) && allowedTypes.contains(o2.getClass()))) {
throw new UnsupportedOperationException("Allowed Types:" + allowedTypes);
}
}
return d1.compareTo(d2);
}
});
更新2:
List<Number> li = Constraints.constrainedList(new ArrayList<Number>(),
new Constraint<Number>() {
HashSet<Class<? extends Number>> allowedTypes;
{
allowedTypes = new HashSet<Class<? extends Number>>();
allowedTypes.add(Integer.class);
allowedTypes.add(Double.class);
allowedTypes.add(Float.class);
allowedTypes.add(Short.class);
allowedTypes.add(Byte.class);
}
@Override
public Number checkElement(Number arg0) {
if (arg0 != null) {
if (allowedTypes.contains(arg0.getClass())) {
return arg0;
}
}
throw new IllegalArgumentException("Type Not Allowed");
}
}
);
li.add(Double.POSITIVE_INFINITY);
li.add(new Integer(20));
li.add(new Double(12.2));
li.add(new Float(1.2));
li.add(Double.NEGATIVE_INFINITY);
li.add(Float.NEGATIVE_INFINITY);
// li.add(null); //throws exception
// li.add(new BigInteger("22"); //throws exception
li.add(new Integer(20));
System.out.println(li);
Collections.sort(li, new Comparator<Number>() {
@Override
public int compare(Number o1, Number o2) {
Double d1 = o1.doubleValue();
Double d2 = o2.doubleValue();
return d1.compareTo(d2);
}
});
System.out.println(li);
这篇关于对列表进行排序< Number>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文