我有一个方法,它以对象的形式接受可变数量和类型的参数。我想仅计算这些参数中数字的中位数。我使用列表插入元素(数字),然后使用集合对列表进行排序。每当我将整数和双精度数作为参数传递时,我都会在 Collections.sort() 行中收到 Classcast 异常。这是我的方法:
public Object median(Object... O) {
List l = new ArrayList<Object>();
for (int i = 0; i < O.length; i++) {
if (Number.class.isAssignableFrom(O[i].getClass())) {
l.add(O[i]);
} else {
try {
double d = Double.parseDouble(O[i].toString());
l.add(d);
} catch (Exception e) {
}
}
}
Collections.sort(l);
double sum = 0;
if (l.size() % 2 == 0) {
if (l.get((l.size()) / 2 - 1) instanceof Double) {
Double d = (Double) l.get((l.size()) / 2 - 1);
sum += d;
} else if (l.get((l.size()) / 2 - 1) instanceof Integer) {
Integer d = (Integer) l.get((l.size()) / 2 - 1);
sum += d;
}
if (l.get((l.size()) / 2) instanceof Double) {
Double d1 = (Double) l.get(l.size() / 2);
sum += d1;
} else if (l.get((l.size()) / 2) instanceof Integer) {
Integer d1 = (Integer) l.get(l.size() / 2);
sum += d1;
}
return sum / 2;
} else {
if (l.get((l.size()) / 2) instanceof Double) {
Double d1 = (Double) l.get(l.size() / 2);
sum = d1;
} else if (l.get((l.size()) / 2) instanceof Integer) {
Integer d1 = (Integer) l.get(l.size() / 2);
sum = d1;
}
return sum;
}
}
我可以以任何方式调用该方法,例如:
System.out.println("中位数------"+cmp.median(13, 18, 13, 14, 13, 16, 14, 21, 13));
System.out.println("中位数---------"+cmp.median(13, 18.1, 13, 14, 13, 16, 14, 21, 13));
System.out.println("中位数---------"+cmp.median(13, 18, 13,"13", 14, 13, 16, 14, 21,13);
System.out.println("中位数---------"+cmp.median(13, 18,"xyz", 13, 14, 13, 16, 14,21,13));
我认为 Collections.sort() 不能与 Doubles 一起使用。请提出出路!