首页 文章

具有许多条件的可比接口

提问于
浏览
0

问题是如何使用可比较的界面和 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 回答

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

    原理很简单:

    • 比较第一对属性。如果它们不同,则返回 negative/positive compare的值;除此以外...

    • 比较第二对属性。如果它们不同,则返回 negative/positive 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

    这是解决 multi-attribute 排序问题的一般方法:

    • 确定排序的属性的有序列表

    • 对于列表中的每个属性,比较双方的值

    • 如果结果不为零,请立即返回

    • 如果结果为零,请转到列表中的下一个属性

    • 如果没有足够的属性,则返回零

    如果属性的数量是固定的,则属性的有序列表上的“循环”将展开 i.e。每个单独的属性分别进行比较:

    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
    

相关问题