我需要一个番石榴MultiSet.Entry的比较器,按count计数和String second排序。但是,我遇到了编译器问题,我想我对泛型有所错误。MultiSet.Entry和泛型的比较器
这编译:
Comparator<Multiset.Entry<String>> comparator() {
return Comparator.comparing(Multiset.Entry::getCount);
}
然而,这并不:
Comparator<Multiset.Entry<String>> comparator() {
return Comparator.comparing(Multiset.Entry::getCount).thenComparing(Multiset.Entry::getElement);
}
Error: java: incompatible types: cannot infer type-variable(s) T,U (argument mismatch; invalid method reference method getCount in interface com.google.common.collect.Multiset.Entry cannot be applied to given types required: no arguments found: java.lang.Object reason: actual and formal argument lists differ in length)
如果我结合比较例如对于字符串,我显然没有类似的问题。
Comparator<String> comparator2() {
return Comparator.comparing(String::length).thenComparing(String::toString);
}
我在这里错过了什么,以及如何才能使它工作?
(注:我知道有可能是与番石榴不同的方法,但我想知道我来到这里的问题。)
我没有声称明白为什么它是必要的,但你可以通过为第一个方法调用添加显式类型参数来获得这些'thenComparing'链。比较器,Integer>比较(Multiset.Entry :: getCount).thenComparing(Multiset.Entry :: getElement);' –
您还应该使用comparatorInt()进行第一次比较:'return Comparator。< Multiset.Entry> ComparisonInt(Multiset.Entry :: getCount).thenComparing(Multiset.Entry :: getElement);' –
comparatorInt()是有意义的,但它仍然需要显式类型参数。为什么需要使用MultiSet.Entry,但不使用String? –