【问题标题】:Order ListView by boolean and double values按布尔值和双精度值排序 ListView
【发布时间】:2014-09-06 08:02:21
【问题描述】:

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

【问题讨论】:

    标签: android listview sorting collections boolean


    【解决方案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;
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-05
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-02-20
      • 1970-01-01
      相关资源
      最近更新 更多