现在,我已经编写了对整数和字符串数组进行排序的比较器。从代码中可以看出,如果两个类不相同,则 String 类将采用大于值。但是,这仅允许两个类。如果我想向数组添加另一个基本类型(例如 Float)怎么办?我必须向 if-else 语句添加更多代码。有没有一种方法可以实现比较,而不必为我想要比较的每个附加类添加语句?
import java.util.Arrays;
import java.util.Comparator;
public class SampleComparator implements Comparator<Object> {
public static void main(String[] args) {
Object[] inputData = { new String("pizza"), new Integer(0),
new String("apples"), new Integer(5), new String("pizza"),
new Integer(3), new Integer(7), new Integer(5) };
Arrays.sort(inputData, new SampleComparator());
System.out.println(Arrays.asList(inputData));
}
public int compare(Object o1, Object o2) {
if (o1.getClass().equals(o2.getClass())) {
return ((Comparable)o1).compareTo((Comparable)o2);
} else {
if(o1.getClass().getCanonicalName().equals("java.lang.String")){
return 1;
} else {
return -1;
}
}
}
}
output:
[0, 3, 5, 5, 7, apples, pizza, pizza]
我必须向 if-else 语句添加更多代码。有没有一种方法可以实现比较,而不必为我想要比较的每个附加类添加语句?
您可能希望使用同一类的本机比较器来比较同一类的对象,然后对类进行某种排序(例如,所有整数之前的所有浮点数之前的所有字符串)。
因此,您可以先比较类,然后如果相等则比较对象。
public int compare(Object o1, Object o2) {
// maybe some null checks here?
if (o1.getClass().equals(o2.getClass())) {
// and what if they are not Comparable ?
return ((Comparable)o1).compareTo((Comparable)o2);
} else {
// for example compare by class name alphabetically
// another idea would be a map with all supported classes,
// assigning them an order
return o1.getClass().getName().compareTo(o2.getClass().getName());
}
}
很难对未知类别进行有意义的比较。您可能需要制定受支持的类的列表以及您希望如何比较它们的明确规则。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)