1. 由大到小排序;
2. 对象数组排序;
1. 由大到小排序;
注意:必需是Integer 类型的数组!!!
方法一:
import java.util.Arrays; import java.util.Comparator; public class Main1 { public static void main(String[] args) { Integer [] array=new Integer[]{1,2,3,4,5}; Arrays.sort(array, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }); for(Integer i : array) { System.out.println(i); } } }
方法二:
import java.util.Arrays; import java.util.Comparator; public class Main1 { public static void main(String[] args) { Integer [] array=new Integer[]{1,2,3,4,5}; Comparator<Integer> cmp = new Comparator<Integer>() { public int compare(Integer a, Integer b) { return b - a; } }; Arrays.sort(array, cmp); for(Integer i : array) { System.out.println(i); } } }
方法三:
import java.util.Arrays; import java.util.Comparator; public class Main1 { public static void main(String[] args) { Integer [] array=new Integer[]{1,2,3,4,5}; Comparator<Integer> cmp = new My_Comparator (); Arrays.sort(array, cmp); for(Integer i : array) { System.out.println(i); } } } class My_Comparator implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return o2 - o1; } }
2. 对象数组排序
import java.util.Arrays; import java.util.Comparator; public class Main1 { public static void main(String[] args) { man[] mans = new man[3]; mans[0] = new man(1); mans[1] = new man(222); mans[2] = new man(5); Comparator<man> cmp = new My_Comparator (); Arrays.sort(mans, cmp); for(man i : mans) { System.out.println(i.a); } } } class My_Comparator implements Comparator<man>{ @Override public int compare(man o1, man o2) { return o2.a - o1.a; } } class man{ public int a; man(int x){ this.a = x; } }