2

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

5
  • just return result straight away :) Commented May 9, 2009 at 14:03
  • @bruno Note that your Comparator does not handle null names. Commented May 9, 2009 at 14:13
  • Why should it if a valid Client object cannot have a null name. Commented May 9, 2009 at 16:59
  • 1
    Side Note: Use compareToIgnoreCase() instead of upper casing the values - it's much more efficient because it (a) enjoys the benefit of early termination, and (b) avoids having to create and collect two new Strings. Commented May 9, 2009 at 22:21
  • Also, there's no point in creating a new comparator each time; just create a static one and reuse it. Commented May 9, 2009 at 22:23

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.