开发者

Fastest way to insert a word at the correct position in a dictionary

开发者 https://www.devze.com 2022-12-10 04:20 出处:网络
Currently, I\'m simply inserting the word into the dictionary (ArrayList<String>) and then sorting the dictionary like so:

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 th开发者_运维问答is 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.


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.
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消