我正在試驗records和流。
我創建了這些記錄來計算文本中的字母數。
record Letter(int code) {
Letter(int code) {
this.code = Character.toLowerCase(code);
}
}
record LetterCount(long count) implements Comparable<LetterCount> {
@Override
public int compareTo(LetterCount other) {
return Long.compare(this.count, other.count);
}
static Collector<Letter, Object, LetterCount> countingLetters() {
return Collectors.collectingAndThen(
Collectors.<Letter>counting(),
LetterCount::new);
}
}
這是使用它們的片段:
final var countedChars = text.chars()
.mapToObj(Letter::new)
.collect(
groupingBy(Function.identity(),
LetterCount.countingLetters() // compilation error
// collectingAndThen(counting(), LetterCount::new) // this line doesn't produce error
));
如果我注釋掉collectingAndThen()用作groupingBy().
但是,當我嘗試LetterCount.countingLetters()用作下游收集器時,編譯器會丟失。
我收到以下錯誤訊息:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Collector cannot be resolved to a type
Type mismatch: cannot convert from Collector<Letter,capture#17-of ?,LetterCount> to Collector<Letter,Object,LetterCount>
The method countingLetters() from the type LetterCount refers to the missing type Collector
The method entrySet() is undefined for the type Object
uj5u.com熱心網友回復:
介面Collector具有以下宣告:
public interface Collector<T,?A,?R>
其中第二個泛型型別引數A表示可變容器的型別,該容器在內部用于累積歸約的結果。這種型別通常被實作隱藏。
您的方法countingLetters()宣告回傳型別如下:
Collector<Letter, Object, LetterCount>
這意味著此方法回傳的收集器的可變容器Object的型別應為.
提醒:泛型是不變的,即如果你說Object你必須只提供Object(不是它的子型別,不是未知型別 ?,只有Object型別本身)。
這是不正確的,原因如下:
JDK 中內置的所有收集器都隱藏了它們的可變容器型別。
conting您在代碼中使用的收集器宣告為 returnCollector<T,?,Long>。在引擎蓋下,它使用,盡管它在內部用作容器summingLong,但反過來又回傳。那是因為暴露這些實作細節是沒有意義的。因此,您宣告的回傳型別的泛型引數不符合您回傳的收集器的泛型引數。即,由于您獲得了未知型別,因此您不能宣告回傳一個.Collector<T,?,Long>long[]?Object即使您不使用內置收集器,而是使用您自己的自定義收集器,公開其容器的實際型別仍然不是一個好主意。只是因為在未來的某個時候,你可能想要改變它。
Object類是不可變的,因此將其用作容器型別(如果您嘗試實作自定義收集器)是徒勞的,因為它無法累積資料。
底線:該方法回傳的收集器中的第二個泛型引數countingLetters()不正確。
要修復它,您必須將可變容器的型別更改為:
- 包含所有可能型別的未知
?型別,即預期提供的收集器可能具有任何型別的可變容器(這就是 JDK 中所有收集器的宣告方式); - 或上限通配符
? extends Object(這基本上是描述未知型別的更詳細的方式)。
public static Collector<Letter, ?, LetterCount> countingLetters()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/464405.html
