compareTo基于两个对象值

时间:2013-09-10 15:26:56

标签: java final 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;
}

程序应实现类似的界面,并应根据状态ASCENDING和销售DESCENDING比较特许经营对象。我的问题是如何使用这两个值进行比较,有没有办法在单个比较中进行比较,还是需要多个比较器?

实施例

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

state = CA,sales = 3300与state = CA相比,sales = 1000将返回NEGATIVE

州= CA,销售= 3300与州= CA相比,销售= 9900将返回POSITIVE

感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

  

有没有办法在单个比较中完成,或者我需要多个比较器吗?

在您的情况下,您不需要多个比较器。只需在单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.
    }
}

答案 1 :(得分:0)

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

答案 2 :(得分:0)

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

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

(或类似的东西)