3 回答
TA贡献1934条经验 获得超2个赞
如果您要查找默认排序,则应使用Comparable而不是Comparator。
看到这里,这可能会有帮助- 类何时应该是Comparable和/或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;
}
}
TA贡献1848条经验 获得超2个赞
按照此代码对任何ArrayList进行排序
Collections.sort(myList, new Comparator<EmployeeClass>(){
public int compare(EmployeeClass obj1, EmployeeClass obj2) {
// ## Ascending order
return obj1.firstName.compareToIgnoreCase(obj2.firstName); // To compare string values
// return Integer.valueOf(obj1.empId).compareTo(Integer.valueOf(obj2.empId)); // To compare integer values
// ## Descending order
// return obj2.firstName.compareToIgnoreCase(obj1.firstName); // To compare string values
// return Integer.valueOf(obj2.empId).compareTo(Integer.valueOf(obj1.empId)); // To compare integer values
}
});
TA贡献1876条经验 获得超6个赞
我认为这会更好地帮助您
Person p = new Person("Bruce", "Willis");
Person p1 = new Person("Tom", "Hanks");
Person p2 = new Person("Nicolas", "Cage");
Person p3 = new Person("John", "Travolta");
ArrayList<Person> list = new ArrayList<Person>();
list.add(p);
list.add(p1);
list.add(p2);
list.add(p3);
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Person p1 = (Person) o1;
Person p2 = (Person) o2;
return p1.getFirstName().compareToIgnoreCase(p2.getFirstName());
}
});
添加回答
举报