Comparator 是 class 还是接口,如果是后者,它如何被实例化?

Is Comparator a class or interface, and, if latter, how come it can be instantiated?

我一直在尝试比较 Java 中的对象,因此比较 ComparableComparator 实体。我一直在阅读 Joshua Bloch 的 Effective Java,第三版。

第 70 页:

In Java 8, the Comparator interface was outfitted with a set of comparator construction methods, which enable fluent construction of comparators.In Java 8, the Comparator interface was outfitted with a set of comparator construction methods, which enable fluent construction of comparators.

第 71 页:

The Comparator class has a full complement of construction methods.

那么,是哪个?

我查阅了 java 规范,其中指出 Comparator 确实是一个接口,我假设这是我的问题的正确答案。那么这只是书中的错误吗?

布洛赫接着说:

The static method, named comparing, has two overloadings. One takes a key extractor and uses the keys’ natural order. The second takes both a key extractor and a comparator to be used on the extracted keys. There are three overloadings of the instance method, which is named thenComparing.

如果Comparator是一个接口,它怎么会有实例方法呢?我一直认为接口是不可实例化的。还是我完全看错了?

  1. 正如您所说,它是一个界面。 API 文档在这方面是规范的,因为它是从代码本身生成的。
  2. 因此将其称为 class 是一个小口误。
  3. 尽管 Java 8,interfaces can have non-abstract instance methods, and that's what's going on with thenComparing()。 (注意 default 关键字。)