通过布尔值和双值来命令ListView

时间:2014-07-15 23:30:41

标签: android listview sorting collections boolean

我有一个ListView,它基于listview的每个元素所具有的double值,目前按升序排列。

列表

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值进行排序。现在我希望每个大学对象都有布尔参数。例如,如果某个参数为真,那些大学应该在错误的那些之前,但是对于这两个组,排序仍然应该基于scoreDistance值。我该怎么做呢?

1 个答案:

答案 0 :(得分:1)

首先检查比较器以检查布尔值,然后检查双值,如果两个项的布尔值相同。

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;
}