为什么java.util.Comparator.reversed API不适用于泛型类[重复]

3j86kqsm  于 2023-06-28  发布在  Java
关注(0)|答案(1)|浏览(134)

此问题已在此处有答案

Comparator.reversed() does not compile using lambda(4个答案)
2天前关闭。
下面的代码只在情况4下无法编译:

static class Foo {
    int seq;
    public Foo(int seq) {
      this.seq = seq;
    }

    public int getSeq() {
      return this.seq;
    }
  }

  static class Bar<T> {
    T seq;
    public Bar(T seq) {
      this.seq = seq;
    }

    public T getSeq() {
      return this.seq;
    }
  }

  public static void main(String[] args) {
    List<Foo> foos = List.of(new Foo(1), new Foo(2));

    // case 1 can compile
    List<Foo> fooRet1 = foos.stream()
        .sorted(Comparator.comparing(Foo::getSeq))
        .toList();
    // case 2 can compile
    List<Foo> fooRet2 = foos.stream()
        .sorted(Comparator.comparing(Foo::getSeq).reversed())
        .toList();

    List<Bar<Integer>> bars = List.of(new Bar<Integer>(1), new Bar<Integer>(2));
    // case 3 can compile
    List<Bar<Integer>> barRet1 = bars.stream()
        .sorted(Comparator.comparing(Bar::getSeq))
        .toList();
    // case 4 cannot compile
    // intellij IDEA draws a red line under Bar::getSeq, it says:
    // Non-static method cannot be referenced from a static context
    // which is wired
    List<Bar<Integer>> barRet2 = bars.stream()
        .sorted(Comparator.comparing(Bar::getSeq).reversed())
        .toList();
  }

这种限制从何而来?

6ojccjat

6ojccjat1#

这只是Java编译器的一个弱点,它在使用reversed时无法推断Bar的泛型类型。
您可以显式添加Bar的遗传类型

List<Bar<Integer>> barRet2 = bars.stream()
        .sorted(Comparator.comparing(Bar<Integer>::getSeq).reversed())
        .toList();

相关问题https://stackoverflow.com/a/25173599/1477418

相关问题