如何比较java中的多个类?
现在,我已经编写了对整数和字符串数组进行排序的比较器。从代码中可以看出,如果两个类不相同,则 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;
}
}
}
}
输出:
[0, 3, 5, 5, 7, apples, pizza, pizza]
Right now, I have written at comparator that sorts an array of Integers and Strings. As you can see from the code, if the two classes aren't the same, then the String class takes the greater than value. However, this only allows for two classes. What if I want to add another primitive type to my array, such as Float? I'd have to add more code to to if-else statement. Is there a way to implement compare without having to add a statement for each additional class I want to compare?
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]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能希望使用其本机比较器来比较同一类的对象,然后对类进行某种排序(例如,所有整数在所有浮点数之前,所有字符串之前)。
因此,您可以先比较类,然后如果相等则比较对象。
很难对未知类别进行有意义的比较。您可能需要制定受支持的类的列表以及您希望如何比较它们的明确规则。
You probably want to compare objects of the same class using their native comparators, and then have some order on the classes (e.g.. all ints before all floats before all strings).
So you could compare the classes first, and then if equal compare the objects.
It will be difficult to come up with a meaningful comparison of unknown classes. You probably need to make up a list of supported classes and explicit rules how you want them compared.
如果你只是想确保将课程分组在一起,你可以这样做
If you just want to make sure you group classes together, you could do something like
您始终可以比较
toString()
表示形式:You can always compare the
toString()
representation: