java Arrays.sort () to sort

1, Arrays.sort(int[] a)
which form elements of an array of all sorts, and are in ascending order.

2, Arrays.sort(int[] a, int fromIndex, int toIndex)
which form part of the array is sorted, i.e. the subscript of the array elements to a sorting from fromIndex toIndex-1. Note: the subscript elements not involved in sorting toIndex

3, public static <T> void sort(T[] a,int fromIndex, int toIndex, Comparator<? super T> c)the user can customize the ordering

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 ++) {
             System.out.print(a[i] + " ");
         }
     }
 }
 //Comparator是一个接口,所以这里我们自己定义的类MyComparator要implents该接口 
 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;
         }
     }
     
 }
Published 37 original articles · won praise 30 · views 1139

Guess you like

Origin blog.csdn.net/myjess/article/details/104327416