-1

Currently I am working on a contact manager project where I have a contactMgr class, and a contact class within the contactMgr class that stores a contacts info.

To start out the program, I create a contactMgr array with 20 indices. Then, when I create a contact, that includes name, email and phone number, I then store it in the contactMgr array. All of the fields for the contact object are stored as Strings.

How can I sort the contact objects in the contactMgr array alphabetically by name?

1

1 Answer 1

0

You can use Arrays.sort(T[], Comparator<T>) for this:

ContactMgr[] contacts = ...;
Arrays.sort(contacts, (ContactMgr left, ContactMgr right)
    -> left.getName().compareTo(right.getName())
);

Or if the ContactMgr already implements Comparable interface and it works as comparing the names, you can call Arrays.sort(contact) with default comparator.

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

1 Comment

So I tried implementing the Comparable interface with the Contact class, but it won't let me pass in Contact as an argument to Arrays.sort.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.