Java中Array.sort()的几种用法

Java中Array.sort()的几种用法

Java的Arrays类中有一个sort()方法,该方法是Arrays类的静态方法

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

1、Arrays.sort(int[] a)

对一个数组的所有元素 按从小到大的顺序。

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

运行结果如下:

0 1 2 3 4 5 6 7 8 9

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

对数组部分排序,也就是对数组a的下标从fromIndex到toIndex-1的元素排序

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,int fromIndex, int toIndex, Comparator<? super T> c)

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

注意,要想改变默认的排列顺序,不能使用基本类型(int,double, char)
而要使用它们对应的类

public static void main(String[] args) {
        Integer[] arr = {1, 3, 2, 4, 6, 5};//注意,要想改变默认的排列顺序,不能使用基本类型(int,double, char)
    //而要使用它们对应的类
        Arrays.sort(arr, new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1-o2;
            }
        });
  }

也可以自己实现比较类ArrComparator:

public class Combination {
    public static void main(String[] args) {
    Integer [] arr={1, 3, 2, 4, 6, 5};
    Arrays.sort(arr,new ArrComparator());
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }

    static class ArrComparator implements  Comparator<Integer> {
        public int compare(Integer o1,Integer o2){
            return o2-o1;
        }
    }
}

输出:6 5 4 3 2 1

参考:https://www.tuicool.com/articles/iii6N3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值