简体   繁体   English

泛型和比较器

[英]Generics and Comparator

I am working on generics and found that the following code is giving compile time error at comparing method . 我正在研究generics ,发现以下代码在comparing method时给出了编译时错误。

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 此行的多个标记 - 无法推断用于比较的类型参数(功能) - 类型A未定义适用于此处的m1(对象)

 class A<T> {
    String m1() {
        return null;
    }
}

class B {
    void test() {
        Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1);
    }
}

Can some one help me understand this behavior; 有人可以帮助我理解这种行为; and how can I fix the problem? 我该如何解决这个问题呢?

If you specify the exact generic types at the comparing method, the code compiles. 如果在comparing方法中指定了确切的泛型类型,则代码将进行编译。

Comparator<A<String>> target =
    Comparator.<A<String>, String>comparing(A::m1).thenComparing(A::m1);

您应该为A类指定类型参数。

Comparator<A<String>> target = Comparator.comparing(A<String>::m1).thenComparing(A<String>::m1);

Interesting question. 有趣的问题。 Haven't gone into JLS but I guess type inference does not work in case of chained method call. 没有进入JLS,但我想类型推断在链式方法调用的情况下不起作用。 (You can see it works for a simple Comparator<A<String>> target = Comparator.comparing(A<String>::m1); ) (你可以看到它适用于一个简单的Comparator<A<String>> target = Comparator.comparing(A<String>::m1);

One quick fix, which is similar to another answer, is help Java do the type inference: 一个快速修复,类似于另一个答案,是帮助Java进行类型推断:

Comparator<A<String>> target = Comparator.comparing(A<String>::m1)
                                         .thenComparing(A::m1);

Please note doing it at the first method already do the trick. 请注意,在第一种方法中执行此操作已经可以解决问题。

(Looking forward to see if someone can dig out JLS to see if such inference is supposed to be valid :P ) (期待看看是否有人可以挖出JLS,看看这种推断是否应该是有效的:P)

you can nested as 你可以嵌套为

 Comparator<A<String>> target1 = Comparator.comparing(A::m1);
 Comparator<A<String>> target2 = target1.thenComparing(A::m1);


 myVarList.sort(target2);
 Comparator<A<String>> target = Comparator.comparing(A::m1).thenComparing(A::m1); 

thenComparing()期望Comparator对象作为参数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM