文件GenericInterface.java:
import java.lang.Comparable;
import java.util.function.Function;
public class GenericInterface {
}
interface Comparator<T> {
int compare(T o1, T o2);
static <T, U extends Comparable<?>> //comment out this line
//static <T, U extends Comparable<? super U>> //and uncomment this line to pass compiling
Comparator<T> Comparing(Function<? super T, ? extends U> mapper) {
return new Comparator<T>() {
@Override
public int compare(T o1, T o2) {
return mapper.apply(o1).compareTo(mapper.apply(o2));
}
};
}
//...
}
然后用
javac GenericInterface.java -Xdiags:verbose
用JDK 1.8编译它,导致以下错误:GenericInterface.java:16: error: method compareTo in interface
Comparable<T#2> cannot be applied to given types;
return mapper.apply(o1).compareTo(mapper.apply(o2));
^
required: CAP#1
found: CAP#2
reason: argument mismatch; U cannot be converted to CAP#1
where U,T#1,T#2 are type-variables:
U extends Comparable<?> declared in method <T#1,U>Comparing(Function<? super T#1,? extends U>)
T#1 extends Object declared in method <T#1,U>Comparing(Function<? super T#1,? extends U>)
T#2 extends Object declared in interface Comparable
where CAP#1,CAP#2 are fresh type-variables:
CAP#1 extends Object from capture of ?
CAP#2 extends U from capture of ? extends U
1 error
我可以通过更改此行来通过编译
static <T, U extends Comparable<?>>
对此
static <T, U extends Comparable<? super U>>
但我不知道为什么:
CAP#1 extends Object from capture of ?
CAP#2 extends U from capture of ? extends U
CAP#1和CAP#2不应为
U extends Comparable<?>
吗?谁能告诉我Java如何在上述通用接口的通用方法中捕获类型变量? 最佳答案
您拥有U extends Comparable<?>
的地方compareTo
函数将是int compareTo(? o)
。 ?
是通配符,因此唯一有效的参数是null
。
相反,在具有U extends Comparable<? super U>
的位置将具有int compareTo(? super U o)
,它将采用任何U
。
例如,如果我要声明
class Thing extends Comparable<String> {
int compareTo(String o) { return 0; }
}
然后打电话
Comparator.<Date,Thing>Comparing(myFunc)
我们有一个问题,用一个
Thing.compareTo(String)
参数调用Thing
。(显然,是用简写法表示的。)