java.util.Comparator.reversed API为何不与泛型类一起使用?

huangapple go评论80阅读模式
英文:

Why java.util.Comparator.reversed api does not work with Generic class

问题

这个限制来自于Java的泛型类型参数。在case 4中,Bar::getSeq被尝试用于sorted方法的比较器中,但是由于Bar是一个泛型类,编译器无法确定T的具体类型,因此无法调用非静态方法getSeq。这就是为什么编译器报错说"Non-static method cannot be referenced from a static context"。这个限制是由于泛型类型的擦除机制所导致的,编译器在擦除类型信息后无法确定如何调用泛型对象的实例方法。要解决这个问题,你可以将Bar类的getSeq方法声明为静态方法,或者使用具体类型而不是泛型类型进行操作。

英文:

The following code only cannot compile in case 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();
  }

Where does this limitation come from?

答案1

得分: 1

这只是Java编译器的一个弱点,它无法在使用reversed时推断出Bar的通用类型。

您可以显式添加Bar的通用类型:

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

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

英文:

This is just a weakness in the Java compiler, that it couldn't infer the generic type of Bar while using reversed.

You could explicitly add the genetic type of Bar

List&lt;Bar&lt;Integer&gt;&gt; barRet2 = bars.stream()
        .sorted(Comparator.comparing(Bar&lt;Integer&gt;::getSeq).reversed())
        .toList();

Relevant question https://stackoverflow.com/a/25173599/1477418

huangapple
  • 本文由 发表于 2023年6月25日 19:16:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550134.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定