Java详解Arrays类的sort函数的用法

Java的Arrays类中有一个sort()方法,该方法是Arrays类的静态方法,在需要对数组进行排序时,非常的好用。

但是sort()的参数有好几种,下面我就为大家一一介绍,这几种形式的用法。

1、Arrays.sort(int[] a)

这种形式是对一个数组的所有元素进行排序,并且是按从小到大的顺序。

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        
        int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
        Arrays.sort(a);
        for(int i = 0; i < a.length; i ++) {
            System.out.print(a[i] + " ");
        }
    }
}
``

运行结果如下:

0 1 2 3 4 5 6 7 8 9

2、Arrays.sort(int[] a, int fromIndex, int toIndex)

这种形式是对数组部分排序,也就是对数组a的下标从fromIndex到toIndex-1的元素排序,注意:下标为toIndex的元素不参与排序哦!

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        
        int[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
        Arrays.sort(a, 0, 3);
        for(int i = 0; i < a.length; i ++) {
            System.out.print(a[i] + " ");
        }
    }

}

运行结果如下:

7 8 9 2 3 4 1 0 6 5

上例只是把 9 8 7排列成了7 8 9

3,

public static void sort(T[] a, Comparator<? super T> c) {}

public static void sort(T[] a, int fromIndex, int toIndex, Comparator<? super T> c) {}

上面有一个拘束,就是排列顺序只能是从小到大,如果我们要从大到小,就要使用这种方式

使用比较器(comparator)作为sort的参数(用于单个类型的排序)
package test;

import java.util.Arrays;
import java.util.Comparator;

public class Main {
    public static void main(String[] args) {
        //注意,要想改变默认的排列顺序,不能使用基本类型(int,double, char)
        //而要使用它们对应的类
        Integer[] a = {9, 8, 7, 2, 3, 4, 1, 0, 6, 5};
        //定义一个自定义类MyComparator的对象
        Comparator cmp = new MyComparator();
        Arrays.sort(a, cmp);
        for(int i = 0; i < a.length; i ++) {// int b =Integer.intValue();会自动拆箱
            System.out.print(a[i] + " ");
        }
    }
}
//Comparator是一个接口,所以这里我们自己定义的类MyComparator要implents该接口
//而不是extends Comparator
class MyComparator implements Comparator<Integer>{
    @Override
    public int compare(Integer o1, Integer o2) {
        //如果n1小于n2,我们就返回正值,如果n1大于n2我们就返回负值,
        //这样颠倒一下,就可以实现反向排序了
        if(o1 < o2) { 
            return 1;
        }else if(o1 > o2) {
            return -1;
        }else {
            return 0;
        }
    }
    
}

运行结果如下:

9 8 7 6 5 4 3 2 1 0

主要:如果是要实现对象的排序,则需要用到实现Comparable接口(用于类之间的排序)。

假设有Employee类,有name和salary字段,

需要实现Comparable接口:

public class Employee implements Comparable<Employee> {
    private String name;
    private double salary;
 
    public Employee() {
    }
 
    public Employee(String name, double salary) {
        this.name = name;
        this.salary = salary;
    }
 
    public void raiseSalary(double byPercent) {
        double raise = salary * byPercent / 100;
        salary += raise;
    }
 
    /*
    * Compares employees by salary
    * @param other another Employee object
    * return a negative value if this employee has a lower salary than
    * otherObject , 0 if the salaries are the same, a positive value otherwise
    */
    public int compareTo(Employee other) {
        return Double.compare(salary, other.salary);
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public double getSalary() {
        return salary;
    }
 
    public void setSalary(double salary) {
        this.salary = salary;
    }
}

假设希望根据雇员的薪水进行比较,要实现compareTo方法:

public int compareTo(Object otherObject)
{
    Employee other = (Employee) otherObject;
    return Double.compare(salary, other.salary);
}

我们来测试一下,这个比较排序是否能成功:

import java.util.Arrays;
public class Test {
    public static void main(String[] args) {
        Employee[] staff = new Employee[5];
        staff[0] = new Employee("Harry Hacker", 35000);
        staff[1] = new Employee("Carl Cracker", 75000);
        staff[2] = new Employee("Tony Tester", 38000);
        staff[3] = new Employee("Tony Bool", 48000);
        staff[4] = new Employee("June Bo", 48001);
        Arrays.sort(staff);
        // print out information about all Employee objects
        for (Employee e : staff) {
            System.out.println("name=" + e.getName() + " , salary=" + e.getSalary());
        }
    }
}

输出结果为:

name=Harry Hacker , salary=35000.0
name=Tony Tester , salary=38000.0
name=Tony Bool , salary=48000.0
name=June Bo , salary=48001.0
name=Carl Cracker , salary=75000.0

所以,排序可以实现Comparable接口,然后自定义compareTo方法即可(因为sort方法要有提供对象比较的方式)。

参考链接:
https://www.cnblogs.com/IT-sky/p/3749859.html?utm_source=tuicool&utm_medium=referral
https://blog.csdn.net/qq_20417499/article/details/84849909

  • 0
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值