有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java compareTo基于对象的两个值

我正在做一个“特许经营”计划,它有一个所有者、州和销售,这些都是在构造函数中设置的,不能更改。当我试图编写compareTo方法时,我的问题就出现了

package prob2;

public class Franchise implements Comparable <Franchise>  {
    final String owner;
    final String state;
    final double sales;

protected Franchise(String owner, String state, double sales ) {
    this.owner = owner;
    this.state = state;
    this.sales = sales;
}

public String toString() {
    String str = state + ", " + sales + ", " + owner;
    return str;
}

public String getState() {
    return state;
}

public double getSales() {
    return sales;
}
public int compareTo(Franchise that) {
    double thatSales = that.getSales();
    if (this.getState().compareTo(that.getState()) <0) 
        return -1;
    else if (this.getSales() > thatSales)
        return -1;
    else if (this.getSales() < thatSales)
        return 1;
    else
        return 0;
}

程序应实现可比较的界面,并应根据状态上升和销售下降来比较特许经营对象。我的问题是如何使用这两个值进行比较,是否有一种方法可以在单个比较中进行比较,还是需要多个比较器

例如:

state=CA,sales=3300与state=NC,sales=9900相比将返回负值

state=CA,sales=3300相比state=CA,sales=1000将返回负值

state=CA,sales=3300与state=CA,sales=9900相比将返回正数

谢谢你的帮助


共 (3) 个答案

  1. # 1 楼答案

    您需要通过实现Comparator接口来创建不同的比较器。根据排序参数,您需要在Collections.sort方法中使用适当的comparator类

  2. # 2 楼答案

    当然,您只能在伪代码中使用一个compare方法:

    lessThan(this.state, a.state) && this.sales > a.sales
    

    (或诸如此类)

  3. # 3 楼答案

    is there a way to do it in a single compare, or do i need multiple compareators?

    在您的情况下,您不需要多个比较器。只需基于这两个属性,用单compareTo方法编写逻辑,如下所示:

    public int compareTo(Franchise that) {
        if (this.getState().equals(that.getState()) {
            // Compare on the basis of sales (Take care of order - it's descending here)
        } else {
            // Compare on the basis of states.
        }
    }