我正在开发一个“特许经营”程序,该程序具有所有者、状态和销售额,它们都在构造函数中设置并且无法更改。当我尝试编写 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 比较 Franchise 对象。我的问题是如何使用这两个值进行比较,有没有办法在一次比较中进行比较,或者我需要多个比较器?
例子:
state = CA, sales = 3300 与 state = NC, sales = 9900 相比将返回 NEGATIVE
state = CA, sales = 3300 与 state = CA, sales = 1000 相比,将返回 NEGATIVE
state = CA, sales = 3300 与 state = CA, sales = 9900 相比将返回 POSITIVE
感谢您的任何帮助。