簡體   English   中英

具有許多條件的可比接口

[英]Comparable interface with many conditions

問題是如何使用可比較的接口和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;
}
} 

原理很簡單:

  • 比較第一對屬性。 如果它們不同,則返回負/正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();

一旦發現任何一對屬性之間的差異,這將停止比較。 它仍然會訪問后續的屬性,但是無論如何這應該是一件無關緊要的廉價事情。

這是解決多屬性排序問題的一般方法:

  • 確定排序的屬性的有序列表
  • 對於列表中的每個屬性,比較雙方的值
  • 如果結果不為零,請立即返回
  • 如果結果為零,請轉到列表中的下一個屬性
  • 如果沒有足夠的屬性,則返回零

如果屬性的數量是固定的,則將展開屬性的有序列表上的“循環”,即分別比較每個單獨的屬性:

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

應該這樣做:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM