本文實例為大家分享了java對數組、集合的排序方法,供大家參考,具體內容如下
對數組的排序:
1
2
3
4
5
6
7
8
|
//對數組排序 public void arraySort(){ int [] arr = { 1 , 4 , 6 , 333 , 8 , 2 }; for ( int i= 0 ;i<arr.length;i++){ System.out.println(arr[i]); } } |
對集合的排序:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
//對list升序排序 public void listSort1(){ List<Integer> list = new ArrayList<Integer>(); list.add( 1 ); list.add( 55 ); list.add( 9 ); list.add( 0 ); list.add( 2 ); Collections.sort(list); //使用Collections的sort方法 for ( int a :list){ System.out.println(a); } } //對list降序排序 public void listSort2(){ List<Integer> list = new ArrayList<Integer>(); list.add( 1 ); list.add( 55 ); list.add( 9 ); list.add( 0 ); list.add( 2 ); Collections.sort(list, new Comparator<Integer>() { public int compare(Integer o1, Integer o2) { return o2 - o1; } }); //使用Collections的sort方法,并且重寫compare方法 for ( int a :list){ System.out.println(a); } } |
注意:Collections的sort方法默認是升序排列,如果需要降序排列時就需要重寫conpare方法
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。