Java—集合框架 Collections.sort()、Comparable接口和Comparator接口


  • Collentions工具類--java.util.Collections

  Collentions是Java集合框架中,用來操作集合對象的工具類,也是Java集合框架的成員,與List、Map和Set是並列的。

  Collections.sort() 排序方法,實現對List對象中的元素進行排序.

package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsTest {

    /**
     * Integer泛型的List進行排序
     */
    public void testSort1(){
        List<Integer> integerList = new ArrayList<Integer>();
        //插入10個100以內不重復的隨機整數
        Random random = new Random();
        Integer num;
        for (int i = 0; i < 10; i++) {
            do {
                num = random.nextInt(100);
            } while(integerList.contains(num));
            integerList.add(num);
            System.out.println("成功插入整數:" + num);
        }
        System.out.println("==============排序前=============");
        for (Integer integer : integerList) {
            System.out.print(integer + " ");
        }
        //調用Collections.sort()方法排序
        Collections.sort(integerList);
        System.out.println("==============排序后=============");
        for (Integer integer : integerList) {
            System.out.print(integer + " ");
        }
    }
    /**
     * String泛型的List進行排序
   * 字符串類型進行比較,先數字后字母,數字0-9,字母A-Za-z
*/ public void testSort2() { List<String> stringList = new ArrayList<String>(); //添加3個亂序的String元素 stringList.add("google"); stringList.add("lenovo"); stringList.add("baidu"); System.out.println("==============排序前============="); for (String string : stringList) { System.out.println(string); } Collections.sort(stringList); System.out.println("==============排序后============="); for (String string : stringList) { System.out.println(string); } } public static void main(String[] args) { CollectionsTest ct = new CollectionsTest(); ct.testSort1(); ct.testSort2(); } }
  • Comparable接口和Comparator接口

  在Java中,如果兩個對象需要進行排序,那么它們必須是可以比較的。用Comparable這個接口表示某個對象是可以比較的。Comparable相當於給對象定義了默認的排序規則,而如果改用其他規則進行排序,可用Comparator接口,它定義了臨時比較規則。Comparable接口和Comparator接口,都是Java集合框架的成員。

  Comparable接口:

  1. 實現該接口表示:這個類的實例可以比較大小,可以進行自然排序;
  2. 定義了默認的比較規則
  3. 其 實現類需實現compareTo()方法
  4. Obja.compareTo(Obj2)方法返回正數表示a比b大,負數表示a比b小,0表示a和b相等

  Comparator接口:

  1. 用於定義臨時比較規則,而不是默認比較規則
  2. 其 實現類需要實現compare()方法
  3. 用法:
    Collections.sort(List<T> list, Comparator<? super T> c),根據指定比較器產生的順序對指定列表進行排序。

   實例:學生系列排序,默認按學生id來排序,先隨機生成3個不相同的1000以內的整數做為學生的id;然后再按學生姓名來排序。

package com.test.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class CollectionsTest {

    public void testSort() {
        List<Student> studentList = new ArrayList<Student>();
        List<Integer> studentId = new ArrayList<Integer>();
        Random random = new Random();
        Integer num;
        for (int i = 0; i < 3 ; i++) {
            do {
                num = random.nextInt(1000);
            } while (studentId.contains(num));
            studentId.add(num);
        }

        studentList.add(new Student(studentId.get(0) + "", "Tom"));
        studentList.add(new Student(studentId.get(1) + "", "Jack"));
        studentList.add(new Student(studentId.get(2) + "", "Xiaoming"));
        studentList.add(new Student(1000 + "", "Lily"));
        
        System.out.println("===========排序前=============");
        for (Student student : studentList) {
            System.out.println("學生:" + student.id + "——" + student.name);
        }
        Collections.sort(studentList);
        System.out.println("===========按照id排序后=============");
        for (Student student : studentList) {
            System.out.println("學生:" + student.id + "——" + student.name);
        }
        System.out.println("===========按照姓名排序后========");
        Collections.sort(studentList, new StudentComparator());
        for (Student student : studentList) {
            System.out.println("學生:" + student.id + "——" + student.name);
        }
    }
    
    public static void main(String[] args) {
        CollectionsTest ct = new CollectionsTest();
        ct.testSort();
    }

}

  執行結果:

===========排序前=============
學生:118——Tom
學生:460——Jack
學生:51——Xiaoming
學生:1000——Lily
===========排序后=============
學生:1000——Lily
學生:118——Tom
學生:460——Jack
學生:51——Xiaoming
===========按照姓名排序后========
學生:460——Jack
學生:1000——Lily
學生:118——Tom
學生:51——Xiaoming

  其中,Student類需要實現Comparable接口的compareTo()方法,StudentComparator類需要實現Comparator接口的compare()方法:

  Student.java

package com.test.collection;

import java.util.HashSet;
import java.util.Set;
/**
 * 學生類
 * @author Administrator
 *
 */
public class Student implements Comparable<Student> {
    public String id;
    public String name;
    public Set<Course> courses;//所選課程
    public Student(String id, String name) {
        this.id = id;
        this.name = name;
        this.courses = new HashSet<Course>();//實例化sourses(Set是接口,接口不能被直接實例化)
    }
    @Override
    public int compareTo(Student o) {
        return this.id.compareTo(o.id);
    }
}

   StudentComparator.java

package com.test.collection;

import java.util.Comparator;

public class StudentComparator implements Comparator<Student> {
    @Override
    public int compare(Student o1, Student o2) {
        return o1.name.compareTo(o2.name);
    }
}

 


免責聲明!

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



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