GermainGum
GermainGum

Reputation: 1399

Datastructure : hashmap vs linkedhashmap vs treemap

I saw there are a lot of questions about the differences between these three. Tell me if I am wrong, but if I sum up what I could read:

My question is : Why do we need to maintain insertion order or elements sorted, if at the end the performance to insert, lookup.. are better with hashmap?

Upvotes: 0

Views: 2040

Answers (2)

mrcrag
mrcrag

Reputation: 352

I use Treemap and LinkedHashMap because, while I can sort a HashMap myself, I doubt my solution will be as fast or memory efficient as Java's.

Upvotes: 1

user395760
user395760

Reputation:

We sometimes need to main insertion order because we need the insertion order to solve the problem at hand. Sounds a bit tautological, but that's really pretty much the reason. Some data is ordered but also benefits from random access.

Likewise for sorting. It gives a way to find the "next" or "previous" item very cheaply, while still being reasonably efficient for arbitrary lookup. One example are approximate lookups, say, you know the entry you're looking for starts with Foo but you don't know what the rest of the key is.

Hashmap exists to make things faster and simpler (no concept of order) when you don't need any of these operations, only exact lookup.

Upvotes: 2

Related Questions