java中Collections.sort()方法實現集合排序


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());

   這樣就能忽略上面的默認規則,實現按照新的規則(姓名排序)排序了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM