Comparable用法,集合对象中元素排序
对象实现Comparable接口,用Collections来对List中的对象按某个属性进行排序
?
由于String和Integer是已经实现了Comparable接口,所以可以直接用Collections来排序
?
public class TestCollections { public static void main(String[] args) { List<StudentDO> studentList=new ArrayList<StudentDO>(); StudentDO stu1=new StudentDO(); stu1.setId(1); stu1.setName("list"); stu1.setSex(2); StudentDO stu2=new StudentDO(); stu2.setId(1); stu2.setName("array"); stu2.setSex(2); StudentDO stu3=new StudentDO(); stu3.setId(1); stu3.setName("collection"); stu3.setSex(2); studentList.add(stu1); studentList.add(stu2); studentList.add(stu3); Collections.sort(studentList); System.out.println("=======升序================"); for (StudentDO studentDO : studentList) { System.out.println(studentDO.getName()); } Collections.reverse(studentList); System.out.println("=======降序================"); for (StudentDO studentDO : studentList) { System.out.println(studentDO.getName()); } }}