java中Collections.sort()方法实现集合排序

时间:2023-03-08 19:55:15

1.Integer/String泛型的List进行排序

List <Integer> integerlist = new ArrayList<Integer>();   //定义一个Integer泛型的List

然后用add()方法添加一些Integer类型的数据到该List中,

Collections.sort(integerlist);                                //因为是数值型的数据,排序即按照大小升序排序

2.自定义泛型的List进行排序

其实Collections.sort(List)方法进行排序的前提是:List对象中的泛型类实现了Comparable接口;

我们拿学生类来用具体的代码演示一下:

public class Student implements Comparable<Student>{

int id;

String name;

........

public int compareTo(Student o){               //实现接口自然要实现接口的方法

return  this.id.compareTo(o.id);      //规定学生对象排序的依据,这里按ID排序

}

}

然后就可以对一个由学生对象组成的List表进行Collections.sort(List)排序了(其实是按ID排序)

Comparable接口定义的规则是默认规则。

3.Comparator接口

这个接口可以帮助我们事先定义好各种比较规则,用的时候直接换规则,不用去改泛型对象里

的比较方法compareTo(),

ID排序规则(类):

public class comparebyid implements Comparator<Student>{

public int compare(Student o1,Student o2){

return o1.id.compareTo(o2.id);

}

}

Name排序规则(类):

public class comparebyname implements Comparator<Student>{

public int compare(Student o1,Student o2){

return o1.name.compareTo(o2.name);

}

}

规则定义好了,如何使用呢?

先实例化一个规则对象,将对象传入Collections.sort()方法中:

Collections.sort(studentlist,new comparebyname());

这样就能忽略上面的默认规则,实现按照新的规则(姓名排序)排序了。