![](/img/trans.png)
[英]bound mismatch error in java generic method when using self-referring type
[英]Generic type mismatch while using a Collector returned by the method - Java 17
我正在试验records
和streams 。
我创建了这些记录来计算文本中的字母数。
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
接口Collector
具有以下声明:
public interface Collector<T,A,R>
其中第二个泛型类型参数A
表示可变容器的类型,该容器在内部用于累积归约结果。 这种类型通常被实现隐藏。
您的方法countingLetters()
声明返回类型如下:
Collector<Letter, Object, LetterCount>
这意味着此方法返回的收集器的可变容器类型应为Object
。
提醒: generics 是不变的,即如果你说Object
你必须只提供Object
(不是它的子类型,不是未知类型?
,只有Object
类型本身)。
由于以下几个原因,这是不正确的:
JDK 中内置的所有收集器都隐藏了它们的可变容器类型。 您在代码中使用的收集器条件声明返回conting
Collector<T,?,Long>
。 在引擎盖下,它使用summingLong
,它反过来返回Collector<T,?,Long>
尽管它在内部使用long[]
作为container 。 那是因为公开这些实现细节没有意义。 因此,您声明的返回类型的通用参数不符合您要返回的收集器的通用参数。 即因为你被赋予了未知类型?
,您不能声明返回Object
。
即使您不使用内置收集器,而是使用您自己的自定义收集器,公开其容器的实际类型仍然不是一个好主意。 仅仅是因为在未来的某个时候,您可能想要更改它。
Object
class 是不可变的,因此将其用作容器类型(如果您尝试实现自定义收集器)是徒劳的,因为它无法累积数据。
底线: countingLetters()
方法返回的收集器中的第二个通用参数不正确。
要修复它,您必须将可变容器的类型更改为:
?
它包含所有可能的类型,即预期提供的收集器可能具有任何类型的可变容器(这就是 JDK 中所有收集器的声明方式);? extends Object
? extends Object
(这基本上是描述未知类型的更详细的方式)。public static Collector<Letter, ?, LetterCount> countingLetters()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.