问题是如何使用可比较的界面和 collections.sort 进行型号,产量和价格的分类。我可以在“ public int compareto(car other)”中按升序进行这三种排序吗?
例如,它将按字母顺序与模型一起排序。如果型号相同,则按字母顺序与生产进行排序。如果产量也相同,则最终按价格升序排序。
谢谢您的关注,我困扰了很多天。请帮我。
public static void main(String[] args) {
ArrayList<Car> car = new ArrayList<car>();
// something ignored//
Collections.sort(car); <----------------------Problem
for (Car c : car) {
System.out.println(c);
}
}
class car implements Comparable<car>{
protected String model;
protected String production;
protected int price;
public Tablet(String model ,String production , int price)
{
this.model=model;
this.price=price;
this.production = production;
}
public int compareTo (car other)
{
?????????????????
}
}
class mini-bus extends car
{
private door;
public Tablet(String model ,String production , int price ,int door)
{
super(model , production , price);
this.door = door;
}
}
3 回答
应该这样做:
原理很简单:
比较第一对属性。如果它们不同,则返回 negative/positive
compare
的值;除此以外...比较第二对属性。如果它们不同,则返回 negative/positive
compare
的值;除此以外......(重复使用尽可能多的属性对)...
比较最后一对属性。这是最后一个属性,因此返回
compare
值。例如:
请注意,Guava 中还有一个不错的类,名为
ComparisonChain
,它减少了很多样板逻辑:一旦发现任何一对属性之间的差异,这将停止比较。它仍然会访问后续的属性,但是无论如何这应该是一件无关紧要的廉价事情。
这是解决 multi-attribute 排序问题的一般方法:
确定排序的属性的有序列表
对于列表中的每个属性,比较双方的值
如果结果不为零,请立即返回
如果结果为零,请转到列表中的下一个属性
如果没有足够的属性,则返回零
如果属性的数量是固定的,则属性的有序列表上的“循环”将展开 i.e。每个单独的属性分别进行比较: