Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, which is the most recommended class for a dictionary data structure?

I need a data structure to store users which should be retrieved by id. I noticed there are several classes that implement the Map interface. Which one should be my default choice? They all seem quite equivalent to me.

like image 892
snakile Avatar asked Jan 04 '10 15:01

snakile


People also ask

Which data structure is best for dictionary?

If we want both operations, look up and prefix search, Trie is suited. With Trie, we can support all operations like insert, search, delete in O(n) time where n is length of the word to be processed. Another advantage of Trie is, we can print all words in alphabetical order which is not possible with hashing.

What is the dictionary class in Java?

The Dictionary class is the abstract parent of any class, such as Hashtable , which maps keys to values. Every key and every value is an object. In any one Dictionary object, every key is associated with at most one value. Given a Dictionary and a key, the associated element can be looked up.

What is Java dictionary data structure?

A Java dictionary is an abstract class that stores key-value pairs. Given a key, its corresponding value can be stored and retrieved as needed; thus, a dictionary is a list of key-value pairs. The Dictionary object classes are implemented in java. util .

Which data structure is commonly used to store a dictionary?

Different languages enforce different type restrictions on keys and values in a dictionary. Dictionaries are often implemented as hash tables.


1 Answers

Probably it depends on how many users you plan to have and if you will need them ordered or just getting single items by id.

HashMap uses hash codes to store things so you have constant time for put and get operations but items are always unordered.

TreeMap instead uses a binary tree so you have log(n) time for basic operations but items are kept ordered in the tree.

I would use HashMap because it's the simpler one (remember to give it a suitable initial capacity). Remember that these datastructures are not synchronized by default, if you plan to use it from more than one thread take care of using ConcurrentHashMap.

A middle approach is the LinkedHashMap that uses same structure as HashMap (hashcode and equals method) but it also keeps a doubly linked list of element inserted in the map (mantaining the order of insertion). This hybrid has ordered items (ordered in sense of insertion order, as suggested by comments.. just to be precise but I had already specified that) without performance losses of TreeMap.

like image 194
Jack Avatar answered Sep 30 '22 06:09

Jack