Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I implement a Comparator using Generics?

Tags:

java

generics

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

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


2 Answers

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

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.

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

like image 176
basszero Avatar answered May 27 '26 11:05

basszero


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)

like image 44
Brian Agnew Avatar answered May 27 '26 11:05

Brian Agnew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!