Android-java- 如何按对象内的某个值对对象列表进行排序 [英] Android-java- How to sort a list of objects by a certain value within the object
问题描述
我正在尝试按对象中的特定值对对象数组列表进行排序.做这样的事情的最佳方法是什么.我应该将 Collections.sort() 与某种比较器一起使用吗?
Im trying to sort through an arraylist of objects by a particular value within the object. What would be the best approach to do such a thing. Should I use Collections.sort() with some kind of comparator?
我正在尝试按对象在其中一个变量中保存的浮点值对对象列表进行排序.
Im trying to sort a list of objects by a float value they hold in one of the variables.
这是我目前所拥有的:
public class CustomComparator implements Comparator<Marker> {
@Override
public int compare(Mark o1, Mark o2) {
return o1.getDistance().compareTo(o2.getDistance());
}
}
错误状态:无法在基本类型 double 上调用 compareTo(double).
the error states: Cannot invoke compareTo(double) on the primitive type double.
是不是因为比较器不能返回特定类型以外的任何东西?
Is it because a comparator cant return anything other than a certain type?
推荐答案
如果您要寻找的是默认排序,则应使用 Comparable 而不是 Comparator.
You should use Comparable instead of a Comparator if a default sort is what your looking for.
看这里,这可能有帮助 - 什么时候类应该是 Comparable 和/或 Comparator 的?
See here, this may be of some help - When should a class be Comparable and/or Comparator?
试试这个 -
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class TestSort {
public static void main(String args[]){
ToSort toSort1 = new ToSort(new Float(3), "3");
ToSort toSort2 = new ToSort(new Float(6), "6");
ToSort toSort3 = new ToSort(new Float(9), "9");
ToSort toSort4 = new ToSort(new Float(1), "1");
ToSort toSort5 = new ToSort(new Float(5), "5");
ToSort toSort6 = new ToSort(new Float(0), "0");
ToSort toSort7 = new ToSort(new Float(3), "3");
ToSort toSort8 = new ToSort(new Float(-3), "-3");
List<ToSort> sortList = new ArrayList<ToSort>();
sortList.add(toSort1);
sortList.add(toSort2);
sortList.add(toSort3);
sortList.add(toSort4);
sortList.add(toSort5);
sortList.add(toSort6);
sortList.add(toSort7);
sortList.add(toSort8);
Collections.sort(sortList);
for(ToSort toSort : sortList){
System.out.println(toSort.toString());
}
}
}
public class ToSort implements Comparable<ToSort> {
private Float val;
private String id;
public ToSort(Float val, String id){
this.val = val;
this.id = id;
}
@Override
public int compareTo(ToSort f) {
if (val.floatValue() > f.val.floatValue()) {
return 1;
}
else if (val.floatValue() < f.val.floatValue()) {
return -1;
}
else {
return 0;
}
}
@Override
public String toString(){
return this.id;
}
}
这篇关于Android-java- 如何按对象内的某个值对对象列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!