Java常用API(四)

9.6.2 java.util.Comparator定制比較器接口

思考:

  • (1)如果一個(gè)類,沒有實(shí)現(xiàn)Comparable接口,而這個(gè)類你又不方便修改(例如:一些第三方的類,你只有.class文件,沒有源文件),那么這樣類的對(duì)象也要比較大小怎么辦?
  • (2)如果一個(gè)類,實(shí)現(xiàn)了Comparable接口,也指定了兩個(gè)對(duì)象的比較大小的規(guī)則,但是此時(shí)此刻我不想按照它預(yù)定義的方法比較大小,但是我又不能隨意修改,因?yàn)闀?huì)影響其他地方的使用,怎么辦?

JDK在設(shè)計(jì)類庫之初,也考慮到這種情況了,所以又增加了一個(gè)java.util.Comparator接口。

package java.util;

public interface Comparator{
    int compare(Object o1,Object o2);
}

那么我們想要比較某個(gè)類的兩個(gè)對(duì)象的大小,怎么做呢?步驟:

  1. 第一步:編寫一個(gè)類,我們稱之為比較器類型,實(shí)現(xiàn)java.util.Comparator接口,并重寫方法

    方法體就是你要如何指定的兩個(gè)對(duì)象的大小

  2. 第二步:比較大小時(shí),通過比較器類型的對(duì)象調(diào)用compare()方法,將要比較大小的兩個(gè)對(duì)象作為compare方法的實(shí)參傳入,根據(jù)方法的返回值決定誰大誰小。
    • o1對(duì)象大于o2返回正整數(shù)
    • o1對(duì)象小于o2返回負(fù)整數(shù)
    • o1對(duì)象等于o2返回零

代碼示例:定義定制比較器類

package com.atguigu.array;

import java.util.Comparator;

public class StudentScoreComparator implements Comparator {
    @Override
    public int compare(Object o1, Object o2) {
        Student s1 = (Student) o1;
        Student s2 = (Student) o2;
        int result = s1.getScore() - s2.getScore();
        return result!= 0? result : s1.getId() - s2.getId();
    }
}

代碼示例:測(cè)試類

package com.atguigu.array;

public class TestComparator {
    public static void main(String[] args) {
        Student[] arr = new Student[5];
        arr[0] = new Student(3,"張三",90,23);
        arr[1] = new Student(1,"熊大",100,22);
        arr[2] = new Student(5,"王五",75,25);
        arr[3] = new Student(4,"李四",85,24);
        arr[4] = new Student(2,"熊二",85,18);

        //單獨(dú)比較兩個(gè)對(duì)象
        System.out.println(arr[0].compareTo(arr[1]));
        System.out.println(arr[1].compareTo(arr[2]));
        System.out.println(arr[2].compareTo(arr[2]));

        System.out.println("所有學(xué)生:");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        System.out.println("按照學(xué)號(hào)排序:");
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < arr.length-i; j++) {
                if(arr[j].compareTo(arr[j+1])>0){
                    Student temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        System.out.println("按照成績(jī)排序");
        StudentScoreComparator sc = new StudentScoreComparator();
        for (int i = 1; i < arr.length; i++) {
            for (int j = 0; j < arr.length-i; j++) {
                if(sc.compare(arr[j],arr[j+1])>0){
                    Student temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

9.6.3 對(duì)象數(shù)組的排序和二分查找等

在Arrays數(shù)組工具類中包含如下方法,可以實(shí)現(xiàn)對(duì)象數(shù)組的排序和二分查找等:

  • static void sort(Object[] a) :根據(jù)元素的自然順序?qū)χ付▽?duì)象數(shù)組按升序進(jìn)行排序。
  • static <T> void sort(T[] a, Comparator<? super T> c) :根據(jù)指定比較器產(chǎn)生的順序?qū)χ付▽?duì)象數(shù)組進(jìn)行排序。
  • static int binarySearch(Object[] a, Object key) :要求數(shù)組有序,在數(shù)組中查找key是否存在,如果存在返回第一次找到的下標(biāo),不存在返回負(fù)數(shù)
package com.atguigu.array;

import java.util.Arrays;

public class TestArraysSort {
    public static void main(String[] args) {
        Student[] arr = new Student[5];
        arr[0] = new Student(3,"張三",90,23);
        arr[1] = new Student(1,"熊大",100,22);
        arr[2] = new Student(5,"王五",75,25);
        arr[3] = new Student(4,"李四",85,24);
        arr[4] = new Student(2,"熊二",85,18);

        System.out.println("所有學(xué)生:");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
        System.out.println("按照學(xué)號(hào)排序:");
        Arrays.sort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }

        System.out.println("按照成績(jī)排序");
        StudentScoreComparator sc = new StudentScoreComparator();
        Arrays.sort(arr,sc);
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}
package com.atguigu.array;

import java.util.Arrays;

public class TestArraysBinarySearch {
    public static void main(String[] args) {
        Student[] arr = new Student[5];
        arr[0] = new Student(1,"張三",90,23);
        arr[1] = new Student(2,"熊大",100,22);
        arr[2] = new Student(3,"王五",75,25);
        arr[3] = new Student(4,"李四",85,24);
        arr[4] = new Student(5,"熊二",85,18);

        int index = Arrays.binarySearch(arr, new Student(3, "王五", 75, 25));
        System.out.println("index = " + index);
    }
}