按布尔值和双精度值排序ListView



我有一个ListView,它目前是根据ListView中每个元素的双精度值升序排列的。

列表
public class CollegeList extends ListActivity {
ArrayList<CollegeItem> collegeLists=new ArrayList<CollegeItem>();
ArrayList<String> nameList = new ArrayList<String>();
Comparator<CollegeItem> compareByScoreDistance = new Comparator<CollegeItem>(){
    public int compare(CollegeItem a, CollegeItem b){
        return Double.compare(a.getScoreDistance(), b.getScoreDistance());
    }
};

CollegeItem michigan = new CollegeItem(3.79,30,2020,"University of Michigan","Ann Arbor, Michigan");
CollegeItem berkeley = new CollegeItem(3.84,30,2040,"University of California Berkeley","Berkeley, California");
CollegeItem stanford = new CollegeItem(3.96,33,2215,"Stanford University","Stanford, California");

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    collegeLists.add(michigan);
    collegeLists.add(berkeley);
    collegeLists.add(stanford); 
    Collections.sort(collegeLists, compareByScoreDistance);
    for(CollegeItem collegeList : collegeLists){
        nameList.add(collegeList.getName());
    }
    setListAdapter(new ArrayAdapter<String>(CollegeList.this, android.R.layout.simple_list_item_1, nameList));

}
private class CollegeItem {
private double gpa;
private int act;
private int sat;
private String name;
private String location;
private double score;
private double scoreDistance;
public CollegeItem(double gpa, int act, int sat, String name, String location){
    this.gpa = gpa;
    this.act = act;
    this.sat = sat;
    this.name = name;
    this.location = location;
    if(act/36.0>sat/2400.0){
        this.score = 0.6*gpa*25.0+0.4*(act/36.0)*100.0;
    }else{
        this.score = 0.6*gpa*25.0+0.4*(sat/2400.0)*100.0;
    }
    this.scoreDistance = Math.abs(this.score-MainActivity.scoreDouble)/MainActivity.scoreDouble;
}
public String getName(){
    return this.name;
}
public String getLocation(){
    return this.location;
}
public double getScoreDistance(){
    return this.scoreDistance;
}
}
}

在本例中,按scoreDistance值升序排序。现在我想让每个college对象都有布尔参数。例如,如果某个参数为真,那么这些大学应该排在为假的大学之前,但是在这两组中,排序仍然应该基于scoreDistance值。我该怎么做呢?

编写比较器,首先检查布尔值,然后检查两个项目的布尔值是否相同。

public int compare(CollegeItem a, CollegeItem b) {
    int result = Boolean.compare(a.getBoolean(), b.getBoolean());
    if (result == 0) {
        // boolean values the same
        result = Double.compare(a.getScoreDistance(), b.getScoreDistance());
    }
    return result;
}

最新更新