[英]Understanding comparator usage
while looking at a simple Comparator usage example: 在查看一个简单的Comparator用法示例时:
Comparator<Developer> byName = new Comparator<Developer>() {
@Override
public int compare(Developer o1, Developer o2) {
return o1.getName().compareTo(o2.getName());
}
I'm having trouble understanding this method declaration I've never seen such thing before. 我在理解这个方法声明时遇到了麻烦,我以前从未见过这样的事情。
In addition, I tried to do something else: I created a class that have inner classes that implement Comparator: 另外,我尝试做其他事情:创建了一个类,该类具有实现Comparator的内部类:
class Test{
class A implements Comparator<Integer> {
@Override
public int compare(int a, int b) {
// Do something
}
}
class B implements Comparator<Integer> {
@Override
public int compare(int a, int b) {
return a > b ? 1 :A.compare(a, b);
}
}
}
A.compare(a,b) doesn't compile. A.compare(a,b)不编译。 It asks me to to make A and compare static but then I don't override the method compare of the comparator class.
它要求我将A进行比较并进行静态比较,但是然后我不重写比较器类的方法compare。
Plus, saying I want to use the method A in another class 另外,说我想在另一个类中使用方法A
class C {
private int foo(){
Test.A()
}
}
it doesn't work also how do I do that properly? 它也行不通,我该怎么做呢? Any suggestions?
有什么建议么?
When you use a Comparator<Something>
, then you are using a parameterized type (in this case: Something
). 当您使用
Comparator<Something>
,则使用的是参数化类型 (在这种情况下: Something
)。
The method signiture of compare
needs to match this type. compare
的方法签名需要与此类型匹配。
So, try: 因此,请尝试:
public int compare(Integer a, Integer b)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.