廢話不多說直接奉上代碼先:
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
31
32
33
|
import java.util.*; import java.io.*; public class Main{ static int [] dp = new int [ 1010 ]; public static void main(String [] args) throws IOException{ Mouse [] mice = new Mouse [ 1010 ]; FileReader fr= new FileReader( "in.txt" ); //讀取文件 BufferedReader read = new BufferedReader(fr); String str = "" ; int n= 1 ; while ((str = read.readLine())!= null ){ String [] s= str.split( " " ); mice[n] = new Mouse(); //對象實例化,很重要 mice[n].weight = Integer.parseInt(s[ 0 ]); mice[n].speed =Integer.parseInt(s[ 1 ]); n++; } System.out.println(n); Arrays.sort(mice, 1 ,n); //sort(int start,int end) 包括start索引,不包括end索引 for ( int i= 1 ;i<n;i++){ System.out.println(mice[i].weight+ " " +mice[i].speed); } } } class Mouse implements Comparable{ //實現Comparable接口 int weight; int speed; public int compareTo(Object o){ //重寫compareTo方法 Mouse m=(Mouse)o; return weight>m.weight? 1 :(weight==m.weight? 0 :- 1 ); } } |
另附上Arrays.sort用法:
1. 數字排序 int[] intArray = new int[] { 4, 1, 3, -23 };
Arrays.sort(intArray);
輸出: [-23, 1, 3, 4]
2. 字符串排序,先大寫后小寫 String[] strArray = new String[] { "z", "a", "C" };
Arrays.sort(strArray);
輸出: [C, a, z]
3. 嚴格按字母表順序排序,也就是忽略大小寫排序 Case-insensitive sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
輸出: [a, C, z]
4. 反向排序, Reverse-order sort
Arrays.sort(strArray, Collections.reverseOrder());
輸出:[z, a, C]
5. 忽略大小寫反向排序 Case-insensitive reverse-order sort
Arrays.sort(strArray, String.CASE_INSENSITIVE_ORDER);
Collections.reverse(Arrays.asList(strArray));
輸出: [z, C, a]
6、對象數組排序
要對一個對象數組排序 ,則要自己實現java.util.Comparator接口
例子:
Common_User[] userListTemp=new Common_User[temp.size()];
Arrays.sort(userListTemp, new PinyinComparator());
PinyinComparator 實現了Comparator接口,重寫了compare方法,來告訴Arrays按照什么規則來比較兩個對象的大小。
以上所述就是本文的全部內容了,希望大家能夠喜歡。