Collections.sort对象排序失效问题
作者:互联网
今天做一个对象集合排序,看着代码没啥问题,可排序就是不起作用,代码如下。
public static void main(String[] args) {
List<student> list=new ArrayList<>();
student o1=new student();
o1.setTotalNum(10);
o1.setEndNum(2);
student o2=new student();
o2.setTotalNum(8);
o2.setEndNum(2);
student o3=new student();
o3.setTotalNum(100);
o3.setEndNum(2);
list.add(o2);
list.add(o3);
list.add(o1);
Collections.sort(list, new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
return o2.getTotalNum()-o1.getTotalNum();
}
});
System.out.println(list);
}
输出如下,没有进行排序。
[QuarantineInfoController.student(totalNum=100, endNum=2), QuarantineInfoController.student(totalNum=10, endNum=2), QuarantineInfoController.student(totalNum=8, endNum=2)]
最终找到原因,
List<student> list=new ArrayList<>();要改为List<student> list=new ArrayList<student>();
正确代码如下
public static void main(String[] args) {
List<student> list=new ArrayList<student>();
student o1=new student();
o1.setTotalNum(10);
o1.setEndNum(2);
student o2=new student();
o2.setTotalNum(8);
o2.setEndNum(2);
student o3=new student();
o3.setTotalNum(100);
o3.setEndNum(2);
list.add(o2);
list.add(o3);
list.add(o1);
Collections.sort(list, new Comparator<student>() {
@Override
public int compare(student o1, student o2) {
return o2.getTotalNum()-o1.getTotalNum();
}
});
输出:
[QuarantineInfoController.student(totalNum=100, endNum=2), QuarantineInfoController.student(totalNum=10, endNum=2), QuarantineInfoController.student(totalNum=8, endNum=2)]
这样就排序了,小小的细节,大大的问题呀!
标签:sort,list,Collections,student,new,排序,o3,o2,o1 来源: https://blog.csdn.net/letterss/article/details/121094258