+14  A: 

your toString method probably isn't overridden for your objects representing the contacts. It will return a hash string for those objects, which varies every time your app is run.

You can fix this either of two ways:

  • Override the toString() method in your Contact object to return the contact's name (1), or
  • Change the Comparator to Comparator<Contact> so it gets Contact objects as parameters (2)

for (1), add this to your Contact class:

@Override public String toString() {
    return get_contactFirstName();
}

for (2) you would end up with this Comparator implementation:

final static class ContactsListComparator implements Comparator<Contact> {                           
    public int compare(Contact o1, Contact o2) {
        return contact1.get_contactFirstName().compareTo(contact2.get_contactFirstName());
    }
}

you don't even need to check for the <0 or >0, but you can just return whatever the String comparison gives.

Jorn
correct! =) ((ContactsListObject)o1).get_contactFirstName().compareTo(((ContactsListObject)o2).get_contactFirstName())
Henrik P. Hessel
Sweet catch, bravo!
javamonkey79
+2  A: 

I would use:

final static class ContactsListComparator implements Comparator<Contact>
{
public int compare(Contact c1,Contact c2)
 {
 int i=c1.get_contactLastName().compareTo(c2.get_contactLastName());
 if(i!=0) return i;
 return c1.get_contactFirstName().compareTo(c2.get_contactFirstName());;
 }

}
Pierre
Comparator<Contact> needs a least JRE 1.5, doesn't it?
Henrik P. Hessel
yes, generics were introduced in 1.5
Jorn
they won't work in J2ME though - gotta stick to ugly casting!
Marc Novakowski
+2  A: 

Your first example is basically the same as

final static class ContactsListComparator implements Comparator {                           
    public int compare(Object o1, Object o2) {
        return o1.toString().compareTo(o2.toString());
    }    
}

This would work if you override toString() like

public String toString() {
     return _contactFirstName + ' ' + _contactLastName;
}

However, a comparator which compares the intended fields is better as has been suggested.

Peter Lawrey