Java排序方法sort的使用详解

 

对数组的排序:

1 //对数组排序
2 public void arraySort(){
3     int[] arr = {1,4,6,333,8,2};
4     Arrays.sort(arr);//使用java.util.Arrays对象的sort方法
5     for(int i=0;i<arr.length;i++){
6         System.out.println(arr[i]);
7     }
8 }

对集合的排序:

 1 //对list升序排序
 2     public void listSort1(){
 3         List<Integer> list = new ArrayList<Integer>();
 4         list.add(1);
 5         list.add(55);
 6         list.add(9);
 7         list.add(0);
 8         list.add(2);
 9         Collections.sort(list);//使用Collections的sort方法
10         for(int a :list){
11             System.out.println(a);
12         }
13     }
14     //对list降序排序
15     public void listSort2(){
16         List<Integer> list = new ArrayList<Integer>();
17         list.add(1);
18         list.add(55);
19         list.add(9);
20         list.add(0);
21         list.add(2);
22         Collections.sort(list, new Comparator<Integer>() {
23             public int compare(Integer o1, Integer o2) {
24                 return o2 - o1;
25             }
26         });//使用Collections的sort方法,并且重写compare方法
27         for(int a :list){
28             System.out.println(a);
29         }
30     }<br>注意:Collections的sort方法默认是升序排列,如果需要降序排列时就需要重写conpare方法

 

posted @ 2017-10-04 19:59  听见温暖www  阅读(254)  评论(0编辑  收藏  举报