【发布时间】:2022-11-23 01:44:04
【问题描述】:
我有以下课程。我无法满足通用类型。 请帮助我理解这个问题。
我有以下课程。我无法满足通用类型。 请帮助我理解这个问题。
// Requirement is that each implementation of MappedKey should also be sortable. Hence should implement Comparable<ConcreteType>.
public interface MappedKey<T extends MappedKey<T>> extends Comparable<T> {
String displayName();
}
public interface DataMapper<K extends MappedKey<K>, V> {
ImmutableMap<K, ImmutableList<V>> map(List<V> data, Message config);
}
// Call site
Map<MapperType, DataMapper<?, Country>> mappers = getMappers();
ImmutableMap<K, ImmutableList<V>> mapped = mappers.get(MAPPER_TYPE).map(getData());
// Here I want to sort the keys returned by mapper.
List<MappedKey<?>> keys = new ArrayList<>(mapped.keySet()); // Note that this doesn't throw error because type parameter K in DataMapper definition extends MappedKey<K>.
Collections.sort(keys);
运行时出现以下错误。我的理由是类型是满足的。由于MappedKey<?>实现了Comparable<? super T#1>,T#1 = MappedKey<?>满足所有约束。我在这里错过了什么?谢谢
no suitable method found for sort(List<MappedKey<?>>)
Collections.sort(keys);
^
method Collections.<T#1>sort(List<T#1>) is not applicable
(inference variable T#1 has incompatible bounds
equality constraints: MappedKey<?>
upper bounds: CAP#1,Comparable<? super T#1>)
method Collections.<T#2>sort(List<T#2>,Comparator<? super T#2>) is not applicable
(cannot infer type-variable(s) T#2
(actual and formal argument lists differ in length))
where T#1,T#2 are type-variables:
T#1 extends Comparable<? super T#1> declared in method <T#1>sort(List<T#1>)
T#2 extends Object declared in method <T#2>sort(List<T#2>,Comparator<? super T#2>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Comparable<CAP#1> from capture of ?
【问题讨论】:
-
在呼叫站点的第二行中,您输入
ImmutableMap<K, ImmutableList<V>> mapped。K和V声明在哪里? -
?意味着它的意思 - 它不会神奇地更新自己到你正在使用的东西的有效范围?为了。这很不幸,但据我所知,这是一个 Java 限制。您可能只需要在此处接受它,转换为原始类型,然后从那里进行排序 - 并使用@SuppressWarnings消除此转换可能导致的警告。