views:

93

answers:

1

Currently, I'm simply inserting the word into the dictionary (ArrayList<String>) and then sorting the dictionary like so:

dictionary.add(newWord);
Collections.sort(dictionary, new Comparator<String>(){
    public int compare(String s1, String s2) {
        return s1.compareToIgnoreCase(s2);
    }        
});

I'm trying to determine whether this way is really the best. The other way, of course, is to find the correct point in the dictionary and then insert the word there. The problem is, I haven't been able to come up with an efficient/reliable way to find that point within the dictionary. I've got a few ideas flying around in my head but it's really tricky putting pen to paper.

If you have an idea of how to do it, please don't post any massive code answers. This is part of an assignment, so instead of posting code could you walk me through how you'd do it? (maybe in pseudocode?)

Thank you.

+8  A: 

I would use TreeSet<String> instead of ArrayList<String>, because TreeSet uses the String Comparator to maintain the order as you insert. And TreeSet will not allow you to add a null, because it's using the String comparator.

import java.util.Set;
import java.util.TreeSet;

public class Dictionary
{
    public static void main(String[] args)
    {
        Set<String> dictionary = new TreeSet<String>();
        dictionary.add("zebra");
        dictionary.add("wildebeast");
        dictionary.add("aardvark");
        System.out.println(dictionary); // will be in the correct alphabetical order.
    }
}
duffymo
Thanks duffymo!
J-P
You're most welcome. Good luck.
duffymo