1

I have an arrayList of firstName, lastName, address, email, and phoneNumber and an arrayList of multiple "entries" each with all 5 of those indexes. The methods to get and set all 5 of those values are all in the Entry class while adding, modifying, deleting, and sorting entries is done in the class Contact List.

I'm trying to sort the entries by last name and print them out in the ContactList class. I have:

public void listEntries()
    {
        Collections.sort(entries);

        for (int i = 0; i < entries.size(); i++)
        {

            entries.get(i).print();
        }
    }

I know I'm missing something to define what to sort by, but I'm not even sure if I should be using Collections.sort. Any suggestions?

1
  • It's a good idea to tag questions with the language in question (Java?), so that people who watch that tag will see it. Commented Dec 9, 2012 at 21:47

2 Answers 2

1

Your class with given entry (i think, that Entry is that class) must implements Comparable interface. Then you can use sort on your collection. Order is given by natural ordering (it's up to you to make your own order in implemented method of Comparable interface).

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

2 Comments

Sorry but I'm not very experienced with sorting Collections of Array Lists or implementing "methods of Comparable interfaces". I can easily put import java.util.Comparator; but other than that I'm clueless. I don't know where to put it or what it should contain or if it matters what class i have it in or where i can call the method from. Any additional clues would help.
You have class Entry, that has attributes firstName, lastName, address, email etc. You have also some getters etc. Implementing of Comparable interface is simple. You implement compareTo method in Entry class on attribute you want to sort. For example, you want to sort records on lastName, so method will look like "public int compareTo(Object object) { if (object instanceof Entry) { return lastName.compareTo(((Entry) object).getLastName()); } else ..." check conventions on this method.If you want to sort on more attributes, you can use more comparations
1

You miss a comparator as an extra argument to sort - e.g.

Collections.sort(entries, new Comparator<List<String>>() {
    @Override
    public int compare(List<String> o1, List<String> o2) {
        return o1.get(1).compareTo(o1.get(1));
    }
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.