如何使用泛型实现比较器?

时间:2020-12-05 11:34:09

Just a minor problem with Arraylist. I want to sort a ArrayList<Client> by name.

只是Arraylist的一个小问题。我想按名称对ArrayList 进行排序。

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());
 }

My comparator looks like this:

我的比较器看起来像这样:

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(); 
  }
}

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

如果我使用“implements Comparator ”,我会收到一个错误:“NameComparator不是抽象的,并且不会覆盖java.util.Comparator中的抽象方法比较(Client,Client)。我的比较器错了吗?抱歉这个noob问题,java新手

2 个解决方案

#1


After you implement Comparator<Client> you need to change:

实现Comparator 后,您需要更改:

public int compare(Object client1, Object client) 
{
  ...
}

to this

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);
}

Notice how the generic parameter T shows up in the method name.

注意泛型参数T如何显示在方法名称中。

An IDE like Eclipse / Netbeans / IntelliJ will help out in this situation.

像Eclipse / Netbeans / IntelliJ这样的IDE会在这种情况下提供帮助。

#2


I presume your list of clients is of the type

我假设您的客户列表属于该类型

List<Client>

in which case your comparator should be of type Comparator<Client>, and perform the appropriate comparison (by name, in this case)

在这种情况下,您的比较器应该是Comparator 类型,并执行适当的比较(在这种情况下,按名称)

#1


After you implement Comparator<Client> you need to change:

实现Comparator 后,您需要更改:

public int compare(Object client1, Object client) 
{
  ...
}

to this

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);
}

Notice how the generic parameter T shows up in the method name.

注意泛型参数T如何显示在方法名称中。

An IDE like Eclipse / Netbeans / IntelliJ will help out in this situation.

像Eclipse / Netbeans / IntelliJ这样的IDE会在这种情况下提供帮助。

#2


I presume your list of clients is of the type

我假设您的客户列表属于该类型

List<Client>

in which case your comparator should be of type Comparator<Client>, and perform the appropriate comparison (by name, in this case)

在这种情况下,您的比较器应该是Comparator 类型,并执行适当的比较(在这种情况下,按名称)