2012-05-20 19:54:14Morris
[JAVA] 物件排序實作 Comparable
import java.util.Arrays;
import java.util.Scanner;
public class A {
public static class item implements Comparable{
String name;
int num;
public int compareTo(Object obj) {
item a;
a = (item) obj;
if(this.name.compareTo(a.name) != 0)
return this.name.compareTo(a.name);
return this.num - a.num;
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
item[] A = new item[10];
for(int i = 0; i < 10; i++) {
A[i] = new item();
A[i].name = keyboard.next();
A[i].num = keyboard.nextInt();
}
Arrays.sort(A, 0, 10);
for(int i = 0; i < 10; i++) {
System.out.println(A[i].name + " " + A[i].num);
}
}
}
由於比賽有用到類似的, 因此實做看看, 在此僅提供程式碼
Input:
Jacob 29195
Michael 26991
Joshua 24950
Matthew 23706
Andrew 21852
Joseph 21265
Ethan 21206
Daniel 20947
Christopher 20781
Anthony 19990
Output:
Andrew 21852
Anthony 19990
Christopher 20781
Daniel 20947
Ethan 21206
Jacob 29195
Joseph 21265
Joshua 24950
Matthew 23706
Michael 26991
import java.util.Scanner;
public class A {
public static class item implements Comparable{
String name;
int num;
public int compareTo(Object obj) {
item a;
a = (item) obj;
if(this.name.compareTo(a.name) != 0)
return this.name.compareTo(a.name);
return this.num - a.num;
}
}
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
item[] A = new item[10];
for(int i = 0; i < 10; i++) {
A[i] = new item();
A[i].name = keyboard.next();
A[i].num = keyboard.nextInt();
}
Arrays.sort(A, 0, 10);
for(int i = 0; i < 10; i++) {
System.out.println(A[i].name + " " + A[i].num);
}
}
}
由於比賽有用到類似的, 因此實做看看, 在此僅提供程式碼
Input:
Jacob 29195
Michael 26991
Joshua 24950
Matthew 23706
Andrew 21852
Joseph 21265
Ethan 21206
Daniel 20947
Christopher 20781
Anthony 19990
Output:
Andrew 21852
Anthony 19990
Christopher 20781
Daniel 20947
Ethan 21206
Jacob 29195
Joseph 21265
Joshua 24950
Matthew 23706
Michael 26991