snakile
snakile

Reputation: 54521

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.

Upvotes: 5

Views: 3121

Answers (6)

Mark Bolusmjak
Mark Bolusmjak

Reputation: 24409

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.

Upvotes: 2

Jack
Jack

Reputation: 133599

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.

Upvotes: 10

Powerlord
Powerlord

Reputation: 88796

(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.

Upvotes: 0

Jerome
Jerome

Reputation: 8447

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.

Upvotes: 6

Timothy
Timothy

Reputation: 2477

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.

Upvotes: 1

Powerlord
Powerlord

Reputation: 88796

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

Upvotes: 3

Related Questions