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.
编辑:
这是我到目前为止:
This is what I have so far:
public class CustomComparator implements Comparator<Marker> {
@Override
public int compare(Mark o1, Mark o2) {
return o1.getDistance().compareTo(o2.getDistance());
}
}
错误状态:无法调用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.
看到这里,帮助 - 类应该何时是可比较的和/或比较器?
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屋!