Java 比较器

Java 比较器。Java 的比较器用于给实例添加大小比较的方法,主要有两种: - 实现 Comparable 接口

Java 的比较器用于给实例添加大小比较的方法,主要有两种:

  • 实现 Comparable 接口
  • 实现 Comparator

Comparable

1
2
3
public interface Comparable<T> {
    public int compareTo(T o);
}

实现这个接口后,该实例相互间使用 compareTo 方法中的逻辑比较大小。大部分情况下,比较工具也会使用实例的 compareTo 方法。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
class A implements Comparable<A> {
    private int count;

    public int getCount() {
        return count;
    }

    public A(int count) {
        this.count = count;
    }

    @Override
    public int compareTo(A o) {
        return count - o.getCount();
    }
}

// 实例比较
A a1 = new A(12);
A a2 = new A(13);
int i = a1.compareTo(a2);

Comparator

自定义新的比较器。Comparable 用于一般比较,对于需要自定义比较时,通常选用 Comparator。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class A {
    private int count;

    public int getCount(){
        return this.count;
    }
}

// 自定义比较
List<A> list = Arrays.asList(
    new A(3),
    new A(2),
    new A(1),
    new A(4)
);
list.sort((a,b)->a.getCount()-b.getCount());

Comparator 的几种创建方法:

  • Lambda
1
(a, b) -> a.getCount() - b.getCount()
  • 新建 Comparator 实例
1
2
3
4
5
6
Comparator<A> comparator = new Comparator<A>() {
    @Override
    public int compare(A o1, A o2) {
        return o1.getCount() - o2.getCount();
    }
};
  • Lambda 新建 Comparator 实例
1
Comparator<A> comparator = (o1, o2) -> o1.getCount() - o2.getCount()
Licensed under CC BY-NC-SA 4.0
Gear(夕照)的博客。记录开发、生活,以及一些不足为道的思考……