Java 自定義物件 排序 implements Comparable
定義物件
class Pair implements Comparable<Pair> {
/*
自定義object implements Comparable
42.07%
*/
int n;
int f;
public Pair(int n, int f) {
this.n = n;
this.f = f;
}
public int compareTo(Pair o) {
if (this.f == o.f) return o.n - this.n; // desc
return this.f - o.f; // aces
}
}
之後排序可以使用
Collections.sort(l);
其中 List<Pair> l = new ArrayList<>();
留言
張貼留言