方法一 排序函数直接嵌入
代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<Integer>();
list.add(55);
list.add(48);
list.add(5);
list.add(8);
list.add(4);
list.add(7);
list.add(55);
Collections.sort(list, new Comparator<Integer>() {
@Override
public int compare(Integer u1, Integer u2) {// 重写 Comparator 函数
if (u1 > u2)
return -1;
else if (u1 < u2)
return 1;
else
return 0;
// 也可以写成 return u2 - u1;
}
});
System.out.println(list);
}
}
输出
[55, 55, 48, 8, 7, 5, 4]
方法二 外部类中定义排序函数
代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<A> l1 = new ArrayList<A>();
l1.add(new A(sc.nextDouble(), "W"));
l1.add(new A(sc.nextDouble(), "T"));
l1.add(new A(sc.nextDouble(), "L"));
List<A> l2 = new ArrayList<A>();
l2.add(new A(sc.nextDouble(), "W"));
l2.add(new A(sc.nextDouble(), "T"));
l2.add(new A(sc.nextDouble(), "L"));
List<A> l3 = new ArrayList<A>();
l3.add(new A(sc.nextDouble(), "W"));
l3.add(new A(sc.nextDouble(), "T"));
l3.add(new A(sc.nextDouble(), "L"));
Collections.sort(l1);
Collections.sort(l2);
Collections.sort(l3);
}
}
class A implements Comparable<A> {
double num;
String str;
public A(double num, String str) {
this.num = num;
this.str = str;
}
@Override
public int compareTo(A a) {
if (a.num > num)
return -1;
else if (a.num < num)
return 1;
else
return 0;
}
}
输入
1.1 2.5 1.7
1.2 3.1 1.6
4.1 1.2 1.1
结果