1

I have an ArrayList "contactList" in the class "ContactGroup" that contains an object of another class "Contact". The object contains a String for "name" and an int for "phoneNum".

How do I sort the ArrayList in alphabetically order? Any help would be much appreciated

I tried unsuccessfully using:

 Collections.sort(contactList);
fmorgan91
  • 13
  • 3

5 Answers5

1

You have to implement the Comparable interface. Look it up on the web, your code should result in something like this:

public class Contact implements Comparable<Contact> {

...

    public int compareTo(Contact c) {
        return c.getString().compareTo(this.string)
    }
}

Assuming the string is stored in a variable String string.

Now try to sort!

ShellFish
  • 4,351
  • 1
  • 20
  • 33
1

Your Contact type should implement Comparable:

public class Contact implements Comparable<Contact>
{
 @Override
    public int compareTo(Contact o) {
        return o.name.compareTo(name);
    }
}
Hussein Zawawi
  • 2,907
  • 2
  • 26
  • 44
1
ArrayList<Contact> l = new ArrayList<Contact>();
l.sort(new Comparator<Contact>(){
    @Override
    public int compare(Contact o1, Contact o2){        
        return o1.getName().toLowerCase().compareTo(o2.getName().toLowerCase());
    }           
});
Suspended
  • 1,184
  • 2
  • 12
  • 28
1

This way is fairly simple:

Collections.sort(list, String.CASE_INSENSITIVE_ORDER);

Edit I hit the post button to fast. You need to make your Contact class comparable for Collections.sort(list) to work so it knows which field to use for sorting (you can use comparable for more advanced sorting, but here all you need is to use the name to sort). To do this just add implements Comparable<Contact> to your Contact class and implement the one method in this interface compareTo(Contact o) like so:

public class Contact implements Comparable<Contact> {

    public int compareTo(Contact o) {
         return name.compareToIgnoreCase(o.getName());
    }
}
J Atkin
  • 3,080
  • 2
  • 19
  • 33
0

Try using Comparator:

class ContactComparator implements Comparator<Contact> {
    @Override
    public int compare(Contact c1, Contact c2) {
        return c1.getName().compareToIgnoreCase(c2.getName());
    }
}

//getName being getter for a attribute name(say)
Collections.sort(contactList, new ContactComparator());

In above code snippet, you could also use compare(..) flavor depending upon your requirement.

Then you can sort using Collections.sort(contactList, new ContactComparator());

or you could also make your Contact class implement Comparable, where you could do similar thing as above inside compareTo(..)

and use Collections.sort(contactList);

Mithun
  • 2,075
  • 3
  • 19
  • 26