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

0 votes
asked Jan 4, 2010 by snakile

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.

6 Answers

0 votes
answered Jan 4, 2010 by jerome

No concurrency: use java.util.HashMap

Concurrency: use java.util.concurrent.ConcurrentHashMap

If you want some control on the order used by iterators, use a TreeMap or a LinkedHashMap.

0 votes
answered Jan 4, 2010 by z5h

If they all seem equivalent then you haven't read the documentation. Sun's documentation is pretty much as terse as it gets and provides very important points for making your choices.

Start here.

0 votes
answered Jan 4, 2010 by powerlord

This is covered on the Java Collections Trail, Implementations page.

0 votes
answered Jan 4, 2010 by jack

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.

0 votes
answered Jan 4, 2010 by xxx

Your choice could be modified by how you intend to use the data structure, and where you would rather have performance - reads, or writes?

In a user-login system, my guess is that you'll be doing more reads than writes.

0 votes
answered Jan 4, 2010 by powerlord

(I know I already answered this once, but I feel this needs saying)

Have you considered using a database to store this information? Even if it's SQLite, it'd probably be easier than storing your user database in the program code or loading the entire dataset into memory each time.

Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
Website Online Counter