[英]Cannot infer type argument of Comparator when not using a local variable
在嘗試使用 Comparator 比較和 thenComparing 方法將比較器鏈接在一起時,我遇到了一個奇怪的編譯器錯誤。 我有一個元組列表,我想首先按所有元組的第一個元素對列表進行排序,如果出現重復,我想按第二個元素排序。
在第一次嘗試中,我分階段構建比較器。 元組的第一個元素的比較由局部變量 c1 引用。 然后從該變量構造第二個元素比較器。
在第二次嘗試中,我在沒有任何局部變量的情況下內聯了第一個元素比較器和 go 的構造。 我會假設代碼與之前的嘗試相同,但編譯器突然將代碼標記為編譯時錯誤。
public class Example {
public static class Tuple<A, B> {
private final A a;
private final B b;
public Tuple(A a, B b) {
this.a = a;
this.b = b;
}
public A getA() {return a;}
public B getB() {return b;}
}
{
List<Tuple<Integer, String>> tuples = new ArrayList<>();
Comparator<Tuple<Integer, String>> c1 = Comparator.comparing(Tuple::getA);
// Attemp 1) compiles
tuples.sort(c1.thenComparing(Comparator.comparing(Tuple::getB)));
// Attemp 2) does not compile.
// compiler error: Cannot infer type argument(s) for <T, U> comparing(Function<? super T,? extends U>)
tuples.sort(Comparator.comparing(Tuple::getA).thenComparing(Comparator.comparing(Tuple::getB)));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
}
}
我在這里錯過了一些超級簡單的東西嗎? 在我看來,這樣的內聯永遠不會導致編譯時錯誤。 這可能是編譯器錯誤嗎? 畢竟我使用的是 JDK 14 預覽版。 很高興知道其他人在使用舊 JDK 版本時是否也有這個問題。
As chrylis -cautiouslyoptimistic- has pointed out in a comment this is indeed a problem with the IDE that I am using (in this case I was using Eclipse 2020-06 (4.16.0)) rather than the Java Compiler. 當我使用命令行編譯文件時,它工作正常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.