我有一个特许经营类,拥有者(特许经营权的所有者),州(特许经营权所在州的2个字符的字符串)和销售额(当天的总销售额)
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;
}
}
compareTo基于状态升序和销售降序
import java.util.ArrayList;
import java.util.Collections;
public class FranchiseTester {
public static void main(String[] args) {
ArrayList<Franchise> franchises = new ArrayList<Franchise>();
Franchise a = new Franchise("Andrew Luck", "IN", 1270.5);
Franchise b = new Franchise("Ray Rice", "MD", 1210);
Franchise c = new Franchise("Alfred Morris", "WA", 980.5);
Franchise d = new Franchise("Roddy White", "GA", 670);
Franchise e = new Franchise("Greg Olsen", "SC", 740);
Franchise f = new Franchise("T.Y. Hilton", "IN", 950);
Franchise g = new Franchise("Julio Jones", "GA", 560);
franchises.add(a);
franchises.add(b);
franchises.add(c);
franchises.add(d);
franchises.add(e);
franchises.add(f);
franchises.add(g);
Collections.sort(franchises);
for(int i = 0; i < franchises.size(); i++) {
System.out.print(franchises.get(i) + "\n");
}
}
}
当我在不使用Collections.sort的情况下比较这些专营权对象时,它们会正确比较,但是当我像在这里那样使用Collections.sort进行测试时,会得到如下输出:
GA, 670.0, Roddy White
GA, 560.0, Julio Jones
IN, 1270.5, Andrew Luck
IN, 950.0, T.Y. Hilton
MD, 1210.0, Ray Rice
SC, 740.0, Greg Olsen
WA, 980.5, Alfred Morris
该州的状态仍在正确比较中,但未按销售额正确进行比较(特定统计数据的较低销售额应排在首位)
我认为默认情况下.sort比较字符串是状态仍然正确的原因,我的问题是我也应如何基于销售比较实现它?
解决方法:
在问题陈述中,您说“ compareTo基于状态升序和销售降序”.基于此,您的结果有效.各州按升序排列,每个州的销售按降序排列.在接下来的声明中,您要说(应首先针对特定统计数据降低销售额).因此,基本上您有两个相互矛盾的要求.两者不能同时完成.
换句话说,您是否希望程序执行其他操作,例如两者都应升序或两者都降序或其他顺序.如果是,则必须相应地修改compareTo方法.