【Java 排序】重写Compare方法,实现自己定义排序
生活随笔
收集整理的這篇文章主要介紹了
【Java 排序】重写Compare方法,实现自己定义排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
方法一 排序函數直接嵌入
代碼
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>() {@Overridepublic int compare(Integer u1, Integer u2) {// 重寫 Comparator 函數if (u1 > u2)return -1;else if (u1 < u2)return 1;elsereturn 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;}@Overridepublic int compareTo(A a) {if (a.num > num)return -1;else if (a.num < num)return 1;elsereturn 0;} }輸入
1.1 2.5 1.7 1.2 3.1 1.6 4.1 1.2 1.1結果
總結
以上是生活随笔為你收集整理的【Java 排序】重写Compare方法,实现自己定义排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【PAT甲级 sc.nextInt()的
- 下一篇: 【PAT甲级 ArrayList存放cl