我正在研究泛型,发现以下代码在比较方法时给出了编译时错误.
Multiple markers at this line
– Cannot infer type argument(s) for comparing(Function)
– The type A does not define m1(Object) that is applicable here
class A<T> { String m1() { return null; } } class B { void test() { Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1); } }
有人可以帮助我理解这种行为;我该如何解决这个问题呢?
解决方法
如果在比较方法中指定了确切的泛型类型,则代码将进行编译.
Comparator<A<String>> target = Comparator.<A<String>,String>comparing(A::m1).thenComparing(A::m1);