gpt4 book ai didi

java - 具有多种条件的可比接口(interface)

转载 作者:行者123 更新时间:2023-12-01 16:55:05 24 4
gpt4 key购买 nike

问题是如何使用类似的接口(interface)和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;
}
}

最佳答案

原理非常简单:

  • 比较第一对属性。如果不同,则返回负/正比较值;否则...
  • 比较第二对属性。如果不同,则返回负/正比较值;否则...
  • ...(对尽可能多的属性对重复)...
  • 比较最后一对属性。这是最后一个属性,因此返回比较值。

例如:

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();

一旦发现任何一对属性之间存在差异,就会停止比较。它仍然会访问后续属性,但无论如何,这应该是一件无关紧要的廉价事情。

关于java - 具有多种条件的可比接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34226031/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com