0

I have an object called a Contact that has a bunch of attributes. I also have an array of Contacts called Contact_List, and I have to write a method for the Contact_List that will add a Contact object to it. That part is easy, but it has to ensure that all of the Contacts within it are in order based on their last names. I already have an accessor called getLastName that returns the String of their last name, but how do I make the method add the contact and order them? Please Help, this is due in an hour and a half!

 public void add(Contact frnd)
 {
     if(numContacts == MAX_CONTACTS) // If the List is already full
     {
      System.out.println("The Contact List is already at Maximum Capicity");
     }
     else
     {
      numContacts += 1; // There is one more Contact
      Contact_List[numContacts - 1] = frnd; // Assigns the Last Open Spot the new Contact
     }
 }
  • Here is one example: http://stackoverflow.com/questions/1946668/sorting-using-comparator-descending-order-user-defined-classes/1947527#1947527 – camickr Mar 22 '13 at 02:16

4 Answers4

2

Have a look at Arrays.sort() which accepts a Comparator where you can implement whatever logic you want for ordering your objects. There's also a Collections.sort() if you want to sort Lists instead of arrays.

EDIT: I'm not quite sure I'm doing the right thing, but I'll try to answer your specific question with how I would implement such a requirement in Java. However, this won't be very helpful if you must use an array internally and handle the array (re)allocation and implement the sorting logic manually.

private final Set<Contact> contacts = new TreeSet<Contact>( new Comparator<Contact>() {
    @Override
    public int compare(Contact c1, Contact c2) {
        return c1.getLastName().compareTo(c2.getLastName());
    }
});

public void add(Contact contact) {
    contacts.add(contact);
}

public Contact[] getContacts() {
    return contacts.toArray(new Contact[contacts.size()]);
}

Besides, if the last name provides the natural order of those contacts, I would rather make the Contact class implement Comparable and thus eliminate the need for providing a Comparator to the TreeSet.

Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92
  • I have been trying to figure out how to code that correctly for hours... How do you code it? – Stephen Frazier Mar 22 '13 at 02:03
  • 1
    Do you **need** that to be an array ? Because there are data structures that can be more efficient for this task, like a `TreeSet`. And you can convert that to an array at any time... – Costi Ciudatu Mar 22 '13 at 02:08
  • Besides, did you try googling it ? https://www.google.com/search?q=java+comparator+example. I hope I'm not helping you cheat for something... :) – Costi Ciudatu Mar 22 '13 at 02:10
  • It does have to be an array... And I have googled it, posted a question on Yahoo, Dream in Code, just about everything.... I can use whatever resources I want so Im not cheating lol. Can you please show me how to code it correctly? – Stephen Frazier Mar 22 '13 at 02:15
  • I need to do it the way that Jazzepi is saying to do it below. It seems so simple, but I cannot figure it out.... – Stephen Frazier Mar 22 '13 at 02:55
1

This could work

public static void add(Contact frnd) {
    if (contactList.length == MAX_CONTACTS) {
        throw new IllegalStateException("The Contact List is already at Maximum Capicity");
    }
    int i = Arrays.binarySearch(contactList, frnd, new Comparator<Contact>() {
        public int compare(Contact o1, Contact o2) {
            return o1.getLastName().compareTo(o2.getLastName());
        }
    });
    if (i < 0) {
        i = -i - 1;
    }
    Contact[] temp = new Contact[contactList.length + 1];
    System.arraycopy(contactList, 0, temp, 0, i);
    temp[i] = frnd;
    if (i < contactList.length) {
        System.arraycopy(contactList, i, temp, i + 1, contactList.length - i);
    }
    contactList = temp;
}

But for this task List or TreeSet seem to be more appropriate.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
0

The simplest thing you can do for your example is sort the elements as you add them to the array.

You would replace your

  numContacts += 1; // There is one more Contact
  Contact_List[numContacts - 1] = frnd; // Assigns the Last Open Spot the new Contact

With code that traverses the array and finds the right place to insert the item. INSTEAD of simply placing the item at the end.

For example, let's say you have four people in your array with these last names.

Anthony
Adam
Cindy
Dirk

Now you insert contact Brian

You would want your loop to step through the array, checking the first position to see if it belongs in the 0th index. In this case Anthony comes before Brian, so it doesn't. Then you check the 1st index, but in this case Adam comes before Brian, so it doesn't. Then you check the 2nd index. Aha! Brian comes AFTER Adam, but before Cindy. This is the correct place to insert Brian into your array. Now your array looks like this.

Anthony
Adam
Brian
Cindy
Dirk

If you write the "insert" method in this manner you can guarantee that the array always remains sorted as you add items. Your life will be made a LOT easier by using ArrayList instead of an array. In all the time that I've used Java I've used ArrayList over Array 99.9% of the time.

Jazzepi
  • 5,259
  • 11
  • 55
  • 81
  • How do you code what you are saying... I have been at this project for about 6 hours now, Im running on empty – Stephen Frazier Mar 22 '13 at 02:30
  • You should really take some time to write out a couple of examples on a piece of scratch paper. Like the one I gave above. You should also write out some examples where you have items with similar names, exactly the same names. You should have an example where your list of collections is empty, and then you should start to figure out the algorithm that's going to let you insert your new contact into those examples and make sure it works for all those cases that you've just written down. – Jazzepi Mar 22 '13 at 03:11
  • I would also think about "How would you insert an item into a dictionary, which is ordered alphabetically." because that's going to give you a hint on how you should think about where to insert an item into this array. – Jazzepi Mar 22 '13 at 03:12
  • I know what your saying I have a pile of papers beside me with example/Scratch code, but I cannot get nothing to work... – Stephen Frazier Mar 22 '13 at 03:54
0

The simple solution is to add the contact at the next position (as you are doing now) then sort the array after adding, so it's always in the correct sorted order:

After adding the last contact, use a custom comparator to sort:

if (numContacts == MAX_CONTACTS) {
Arrays.sort(contacts, new Comparator<Contact>() {
    public int compare(Contact o1, Contact o2) {
        return o1.getLastName().compareTo(o2.getLastName());
    }
});
}


Also, these two lines:

numContacts += 1;
Contact_List[numContacts - 1] = frnd;

May be replaced with simply:

Contact_List[numContacts++] = frnd;
Bohemian
  • 412,405
  • 93
  • 575
  • 722
  • That Compiles, but when I go to test it I get a bunch of errors. – Stephen Frazier Mar 22 '13 at 03:49
  • java.lang.NullPointerException at ContactList$1.compare(ContactList.java:54) at ContactList$1.compare(ContactList.java:52) at java.util.TimSort.countRunAndMakeAscending(TimSort.java:324) at java.util.TimSort.sort(TimSort.java:203) at java.util.TimSort.sort(TimSort.java:173) at java.util.Arrays.sort(Arrays.java:659) at ContactList.add(ContactList.java:52) at TestContactList.main(TestContactList.java:17) – Stephen Frazier Mar 22 '13 at 03:49
  • I realised what the problem was: you shouldn't sort until all contacts have been added. I've changed the code to test if the array is full before sorting. Try that. – Bohemian Mar 22 '13 at 05:41