问题是如何使用类似的界面和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;
}
}
答案 0 :(得分:4)
原则很简单:
compare
值;否则... compare
值;否则... compare
值。例如:
int compareModels = this.model.compareTo(that.model);
if (compareModels != 0) {
return compareModels;
}
int compareProd = this.production.compareTo(that.production);
if (compareProd != 0) {
return compareProd;
}
return Integer.compare(this.price, that.price);
请注意,在Guava中还有一个名为ComparisonChain
的好类,它减少了很多这种样板逻辑:
return ComparisonChain.start()
.compare(this.model, that.model)
.compare(this.production, that.production)
.compare(this.price, that.price)
.result();
一旦在任何一对属性之间发现差异,这将停止比较。它仍将访问后续属性,但无论如何这应该是一个无关紧要的廉价事情。
答案 1 :(得分:1)
以下是多属性排序问题的一般方法:
如果属性的数量是固定的,那么&#34;循环&#34;在有序的属性列表上展开,即单独比较每个单独的属性:
int res;
res = this.getA().compareTo(other.getA()); // e.g. model
if (res != 0) return res;
res = this.getB().compareTo(other.getB()); // e.g. production
if (res != 0) return res;
res = this.getC().compareTo(other.getC());
if (res != 0) return res;
...
// For the last attribute return the result directly
return this.getZ().compareTo(other.getZ()); // e.g. price
答案 2 :(得分:0)
这应该做:
public int compareTo(Car other){
if(this.getModel().compareTo(other.getModel()) != 0){
return this.getModel().compareTo(other.getModel());
}else if(this.getProduction().compareTo(other.getProduction()) != 0){
return this.getProduction().compareTo(other.getProduction());
}else{
return Integer.compare(this.getPrice(), other.getPrice());
}
}