如何使用泛型实现比较器? [英] How do I implement a Comparator using Generics?
问题描述
Arraylist
只是一个小问题.我想按名称对 ArrayList< Client>
进行排序.
Just a minor problem with Arraylist
. I want to sort a ArrayList<Client>
by name.
Class Client{ String name; int phonenumber ..}
此代码可以完成工作,但是我收到了编译器警告:使用未经检查或不安全的操作".有什么问题吗?
This code does the work, but i'm having a compiler warning: "uses unchecked or unsafe operations". Whats the problem?
public void sortByName(){
Collections.sort(ListofClients, new NameComparator());
}
我的比较器如下:
public class NameComparator implements Comparator{
public int compare(Object client1, Object client) {
String name1 = ((Client) client1).getName();
String name2 = ((Client) client2).getName();
return name1.toUpperCase()).compareTo(name2.toUpperCase();
}
}
如果我使用" implements Comparator< Client>
",则会出现错误:"NameComparator不是抽象的,并且不会覆盖java.util.Comparator中的抽象方法compare(Client,Client).我的比较器错了吗?对这个新手问题很抱歉,这是Java的新手
If i use "implements Comparator<Client>
" i get a error: "NameComparator is not a abstract and does not override abstract method compare(Client, Client) in java.util.Comparator. Is my comparator wrong? sorry for this noob question, new to java
推荐答案
实现比较器< Client>
后,您需要进行以下更改:
After you implement Comparator<Client>
you need to change:
public int compare(Object client1, Object client)
{
...
}
对此
public int compare(Client client1, Client client)
{
// Now you don't have to cast your objects!
}
这都是因为比较器的定义
this is all because the definition of comparator
public interface Comparator<T>
{
public compare(T o1, T o2);
}
注意方法名称中通用参数T的显示方式.
Notice how the generic parameter T shows up in the method name.
在这种情况下,像Eclipse/Netbeans/IntelliJ这样的IDE会有所帮助.
An IDE like Eclipse / Netbeans / IntelliJ will help out in this situation.
这篇关于如何使用泛型实现比较器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!