tags:

views:

296

answers:

2
+1  Q: 

ArrayList question

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

+3  A: 

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)

Brian Agnew
+10  A: 

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.

basszero
many thanks, it worked!