java中如何不自己写排序方法完成排序
1.如果要排序的东西是放在一个数组里面的
1.1如果要排序的东西是基本数据类型,如int
1 int[] c=new int[]{4,5,1,2,3,6,9}; 2 Arrays.sort(c); 3 Arrays.sort(c,1,4); 4 //无法倒序
1.2如果要排序的东西是java自己的类,如Integer
1 Integer[] b=new Integer[]{4,5,1,2,3,6,9}; 2 Arrays.sort(b); 3 Arrays.sort(b,1,4,Collections.reverseOrder()); 4 Arrays.sort(b, Comparator.reverseOrder()); 5 for(int i=0;i<7;i++) 6 System.out.print(b[i]);
1.3如果要排序的东西是你自己实现的类,那就在类里面直接重写compareTo方法
1 import java.util.*; 2 3 public class Solution{ 4 static class time implements Comparable{ 5 private int a; 6 private int b; 7 8 public time(int a, int b){ 9 this.a=a; 10 this.b=b; 11 } 12 13 public int geta(){ 14 return this.a; 15 } 16 17 public int getb(){ 18 return this.b; 19 } 20 21 @Override 22 public int compareTo(Object o) { 23 time o2=(time)o; 24 return o2.getb()-this.getb(); 25 } 26 } 27 public time[] fun(time[] a){ 28 Arrays.sort(a); 29 return a; 30 } 31 32 33 public static void main(String [] arg){ 34 Solution s=new Solution(); 35 time[] num=new time[]{new time(1,2),new time(2,4),new time(3,3),new time(1,5)}; 36 37 s.fun(num); 38 39 for(int i=0;i<4;i++){ 40 System.out.print(num[i].geta()); 41 System.out.print(" "); 42 System.out.println(num[i].getb()); 43 } 44 45 46 47 } 48 }
2.如果要排序的东西是放在一个List里面的
2.1如果要排序的东西是java自己的类,如Integer,直接在传参的时候传入一个比较器;传入null的话默认升序排列
1 ArrayList<Integer> a=new ArrayList<>(); 2 a.add(4); 3 a.add(5); 4 a.add(1); 5 a.sort(new Comparator<Integer>() { 6 @Override 7 public int compare(Integer o1, Integer o2) { 8 return o2-o1; 9 } 10 });
//a.sort(null);
2.2如果要排序的东西是你自己实现的类,那就在类里面直接重写compareTo方法