-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?

William
  • 429
  • 3
  • 5
  • 16
  • Let `ContractMgr` implement [`Comparable`](https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html), then call [`Array.sort(yourContractMgrArray)`](https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-java.lang.Object:A-). – Turing85 Oct 15 '16 at 23:54

1 Answers1

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.

Zbynek Vyskovsky - kvr000
  • 18,186
  • 3
  • 35
  • 43
  • 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. – William Oct 16 '16 at 00:50