Java常用API(三)

9.5 數(shù)組工具類

9.5.1 java.util.Arrays類

java.util.Arrays數(shù)組工具類,提供了很多靜態(tài)方法來(lái)對(duì)數(shù)組進(jìn)行操作,而且如下每一個(gè)方法都有各種重載形式,以下只列出int[]和Object[]類型的,其他類型的數(shù)組依次類推:

  • 數(shù)組元素拼接
    • static String toString(int[] a) :字符串表示形式由數(shù)組的元素列表組成,括在方括號(hào)("[]")中。相鄰元素用字符 ", "(逗號(hào)加空格)分隔。形式為:[元素1,元素2,元素3。。。]
    • static String toString(Object[] a) :字符串表示形式由數(shù)組的元素列表組成,括在方括號(hào)("[]")中。相鄰元素用字符 ", "(逗號(hào)加空格)分隔。元素將自動(dòng)調(diào)用自己從Object繼承的toString方法將對(duì)象轉(zhuǎn)為字符串進(jìn)行拼接,如果沒(méi)有重寫,則返回類型@hash值,如果重寫則按重寫返回的字符串進(jìn)行拼接。
  • 數(shù)組排序
    • static void sort(int[] a) :將a數(shù)組按照從小到大進(jìn)行排序
    • static void sort(int[] a, int fromIndex, int toIndex) :將a數(shù)組的[fromIndex, toIndex)部分按照升序排列
  • 數(shù)組元素的二分查找
    • static int binarySearch(int[] a, int key)
  • 數(shù)組的復(fù)制
    • static int[] copyOf(int[] original, int newLength) :根據(jù)original原數(shù)組復(fù)制一個(gè)長(zhǎng)度為newLength的新數(shù)組,并返回新數(shù)組
    • static <T> T[] copyOf(T[] original,int newLength):根據(jù)original原數(shù)組復(fù)制一個(gè)長(zhǎng)度為newLength的新數(shù)組,并返回新數(shù)組
    • static int[] copyOfRange(int[] original, int from, int to) :復(fù)制original原數(shù)組的[from,to)構(gòu)成新數(shù)組,并返回新數(shù)組
    • static <T> T[] copyOfRange(T[] original,int from,int to):復(fù)制original原數(shù)組的[from,to)構(gòu)成新數(shù)組,并返回新數(shù)組
  • 比較兩個(gè)數(shù)組是否相等
    • static boolean equals(int[] a, int[] a2) :比較兩個(gè)數(shù)組的長(zhǎng)度、元素是否完全相同
    • static boolean equals(Object[] a,Object[] a2):比較兩個(gè)數(shù)組的長(zhǎng)度、元素是否完全相同
  • 填充數(shù)組
    • static void fill(int[] a, int val) :用val值填充整個(gè)a數(shù)組
    • static void fill(Object[] a,Object val):用val對(duì)象填充整個(gè)a數(shù)組
    • static void fill(int[] a, int fromIndex, int toIndex, int val):將a數(shù)組[fromIndex,toIndex)部分填充為val值
    • static void fill(Object[] a, int fromIndex, int toIndex, Object val) :將a數(shù)組[fromIndex,toIndex)部分填充為val對(duì)象
import org.junit.Test;

import java.text.Collator;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Locale;

public class TestArrays {
    @Test
    public void test01() {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println(Arrays.toString(arr));

        Student[] students = new Student[3];
        students[0] = new Student("張三", 96);
        students[1] = new Student("李四", 85);
        students[2] = new Student("王五", 98);
        System.out.println(Arrays.toString(students));
    }

    @Test
    public void test02() {
        int[] arr = {3, 2, 5, 1, 6};
        System.out.println("排序前" + Arrays.toString(arr));
        Arrays.sort(arr);
        System.out.println("排序后" + Arrays.toString(arr));

        Student[] students = new Student[3];
        students[0] = new Student("張三", 96);
        students[1] = new Student("李四", 85);
        students[2] = new Student("王五", 98);

        System.out.println(Arrays.toString(students));
        Arrays.sort(students);
        System.out.println(Arrays.toString(students));
        Arrays.sort(students, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                return Collator.getInstance(Locale.CHINA).compare(((Student) o1).getName(), ((Student) o2).getName());
            }
        });
        System.out.println(Arrays.toString(students));
    }

    @Test
    public void test03() {
        int[] arr1 = {1, 2, 3, 4, 5};
        int[] arr2 = {1, 2, 3, 4, 5};
        System.out.println(Arrays.equals(arr1, arr2));
    }

    @Test
    public void test04() {
        int[] arr1 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        int[] arr2 = Arrays.copyOf(arr1, 5);
        int[] arr3 = Arrays.copyOfRange(arr1, 3, 8);
        System.out.println(Arrays.toString(arr2));
        System.out.println(Arrays.toString(arr3));

        Arrays.fill(arr1, 5, 9, 3);
        System.out.println(Arrays.toString(arr1));
    }

}
package com.atguigu.arrays;

public class Student implements Comparable {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        return this.score - ((Student)o).score;
    }
}

9.5.2 java.lang.System類

系統(tǒng)類中很多好用的方法,其中幾個(gè)如下:

  • static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length):

    從指定源數(shù)組中復(fù)制一個(gè)數(shù)組,復(fù)制從指定的位置開(kāi)始,到目標(biāo)數(shù)組的指定位置結(jié)束。常用于數(shù)組的插入和刪除

import org.junit.Test;

import java.util.Arrays;

public class TestSystemArrayCopy {
    @Test
    public void test01(){
        int[] arr1 = {1,2,3,4,5};
        int[] arr2 = new int[10];
        System.arraycopy(arr1,0,arr2,3,arr1.length);
        System.out.println(Arrays.toString(arr1));
        System.out.println(Arrays.toString(arr2));
    }

    @Test
    public void test02(){
        int[] arr = {1,2,3,4,5};
        System.arraycopy(arr,0,arr,1,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }

    @Test
    public void test03(){
        int[] arr = {1,2,3,4,5};
        System.arraycopy(arr,1,arr,0,arr.length-1);
        System.out.println(Arrays.toString(arr));
    }
}

9.6 比較器

9.6.1 java.lang.Comparable自然比較器接口

我們知道基本數(shù)據(jù)類型的數(shù)據(jù)(除boolean類型外)需要比較大小的話,之間使用比較運(yùn)算符即可,但是引用數(shù)據(jù)類型是不能直接使用比較運(yùn)算符來(lái)比較大小的。那么,如何解決這個(gè)問(wèn)題呢?

Java給所有引用數(shù)據(jù)類型的大小比較,指定了一個(gè)標(biāo)準(zhǔn)接口,就是java.lang.Comparable接口:

package java.lang;

public interface Comparable{
    int compareTo(Object obj);
}

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

  1. 第一步:哪個(gè)類的對(duì)象要比較大小,哪個(gè)類就實(shí)現(xiàn)java.lang.Comparable接口,并重寫方法

    方法體就是你要如何比較當(dāng)前對(duì)象和指定的另一個(gè)對(duì)象的大小

  2. 第二步:對(duì)象比較大小時(shí),通過(guò)對(duì)象調(diào)用compareTo方法,根據(jù)方法的返回值決定誰(shuí)大誰(shuí)小。
    • this對(duì)象(調(diào)用compareTo方法的對(duì)象)大于指定對(duì)象(傳入compareTo()的參數(shù)對(duì)象)返回正整數(shù)
    • this對(duì)象(調(diào)用compareTo方法的對(duì)象)小于指定對(duì)象(傳入compareTo()的參數(shù)對(duì)象)返回負(fù)整數(shù)
    • this對(duì)象(調(diào)用compareTo方法的對(duì)象)等于指定對(duì)象(傳入compareTo()的參數(shù)對(duì)象)返回零

代碼示例:

package com.atguigu.array;

public class Student implements Comparable {
    private int id;
    private String name;
    private int score;
    private int age;

    public Student(int id, String name, int score, int age) {
        this.id = id;
        this.name = name;
        this.score = score;
        this.age = age;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getScore() {
        return score;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", score=" + score +
                ", age=" + age +
                '}';
    }

    @Override
    public int compareTo(Object o) {
        //這些需要強(qiáng)制,將o對(duì)象向下轉(zhuǎn)型為Student類型的變量,才能調(diào)用Student類中的屬性
        //默認(rèn)按照學(xué)號(hào)比較大小
        Student stu = (Student) o;
        return this.id - stu.id;
    }
}
package com.atguigu.array;

public class TestComparable {
    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]);
        }
    }
}