Is there a Trie in Java?

Belgi picture Belgi · Nov 2, 2011 · Viewed 47.7k times · Source

Possible Duplicate:
Where do I find a standard Trie based map implementation in Java?

I want to use Trie in Java, is there an implementation I can use ? (I tried looking for one but I didn't found it).

Answer

erickson picture erickson · Nov 2, 2011

There is no trie data structure in the core Java libraries.

This may be because tries are usually designed to store character strings, while Java data structures are more general, usually holding any Object (defining equality and a hash operation), though they are sometimes limited to Comparable objects (defining an order). There's no common abstraction for "a sequence of symbols," although CharSequence is suitable for character strings, and I suppose you could do something with Iterable for other types of symbols.

Here's another point to consider: when trying to implement a conventional trie in Java, you are quickly confronted with the fact that Java supports Unicode. To have any sort of space efficiency, you have to restrict the strings in your trie to some subset of symbols, or abandon the conventional approach of storing child nodes in an array indexed by symbol. This might be another reason why tries are not considered general-purpose enough for inclusion in the core library, and something to watch out for if you implement your own or use a third-party library.