Java Comparator类中的泛型。T和U的确切类型是什么?
考虑以下两种方法。它们唯一的区别在于函数的泛型类型声明 T的类型是什么? 我的直觉:Java Comparator类中的泛型。T和U的确切类型是什么?,java,generics,comparator,Java,Generics,Comparator,考虑以下两种方法。它们唯一的区别在于函数的泛型类型声明 T的类型是什么? 我的直觉:T=GamingComputercomparing()接受keyExtractor,其类型为函数。最后,comparating()返回Comparator 这段代码证明了我的直觉,它编译得非常完美: Function<Computer, Property> f1 = Computer::getProperty; Comparator<GamingComputer> c1 = compari
T=GamingComputer
comparing()
接受keyExtractor
,其类型为函数
。最后,comparating()
返回Comparator
这段代码证明了我的直觉,它编译得非常完美:
Function<Computer, Property> f1 = Computer::getProperty;
Comparator<GamingComputer> c1 = comparing(f1);
由于f2
可与所有计算机
配合使用,因此它也应能与任何游戏计算机
配合使用。但是,因为我们没有将类型声明为
我的直觉:T=GamingComputer
你的直觉是正确的
为什么比较器c22=comparingT(计算机::getProperty)代码>编译
这是因为与不变的函数接口实例不同,方法引用是协变和逆变的。使用中的示例,您可以执行以下操作:
// in SomeClass
public static Integer function(Object o) {
return 2;
}
// ...
Function<String, Object> function = SomeCLass::function;
因为f2
本身不是方法引用。这是一个变量
为什么函数f22=GamingComputer::getProperty代码>不编译
f22
将能够接受任何类型的计算机
,因为它接受计算机
。如果你给另一种电脑(不是游戏电脑)f22
,GamingComputer.getProperty
肯定无法处理,是吗?“为什么不编译呢?函数f22=GamingComputer::getProperty;
”这台LHS说它可以使用任何电脑。它不能。RHS说必须花一段时间GamingComputer@Michael然后我又问了我的前一个问题,为什么c22要编译?c22使用我的moded comparingT()方法,该方法中有一个固定的T。然而,我们可以清楚地看到c22由计算机和游戏计算机组成。请不要在一篇文章中写两个问题。我已经编辑过,只包含了问题的更多细节。
List.sort( comparing( Computer::getProperty ) )
Function<Computer, Property> f1 = Computer::getProperty;
Comparator<GamingComputer> c1 = comparing(f1);
Function<Computer, Property> f2 = Computer::getProperty;
Comparator<GamingComputer> c2 = comparingT(f2); // FAILS to compile. Required Type: Comparator<GamingComputer>, Provided Comparator<Computer>
Comparator<Computer> c2 = comparingT(f2); // compiles successfuly
Comparator<GamingComputer> c22 = comparingT(Computer::getProperty); // compiles successfuly... WT, excuse mi French, heck???
Function<Computer, Property> f22 = GamingComputer::getProperty;
java: incompatible types: invalid method reference
method getPart in class function.GamingComputer cannot be applied to given types
required: no arguments
found: function.Computer
reason: actual and formal argument lists differ in length
// in SomeClass
public static Integer function(Object o) {
return 2;
}
// ...
Function<String, Object> function = SomeCLass::function;
Function<GamingComputer, Property> f = Computer::getProperty;
Comparator<GamingComputer> c2 = comparingT(f2);