Difference between HashMap, LinkedHashMap and TreeMap
All three classes implement the Map
interface and offer mostly the same functionality. The most important difference is the order in which iteration through the entries will happen:
HashMap
makes absolutely no guarantees about the iteration order. It can (and will) even change completely when new elements are added.TreeMap
will iterate according to the "natural ordering" of the keys according to theircompareTo()
method (or an externally suppliedComparator
). Additionally, it implements theSortedMap
interface, which contains methods that depend on this sort order.LinkedHashMap
will iterate in the order in which the entries were put into the map
"Hashtable" is the generic name for hash-based maps. In the context of the Java API,Hashtable
is an obsolete class from the days of Java 1.1 before the collections framework existed. It should not be used anymore, because its API is cluttered with obsolete methods that duplicate functionality, and its methods are synchronized (which can decrease performance and is generally useless). Use ConcurrentHashMap instead of Hashtable.
LinkedHashMap and TreeMap which is faster?
LinkedHashMap is faster for insertion because it won´t have to unnecessarily compare values while inserting like TreeMap, as stated by @EJP. And since LinkedHashMap only needs a link for the previous and to the next key, while TreeMap needs a link to the parent node and 1+ links to children, I think that TreeMap will also consume a slightly bigger memory.
So my vote is for LinkedHashMap. Less memory, less time, and of course, less CPU .
Difference between LinkedHashmap and LinkedTreemap
For the performance part:
Hashmap
and LinkedHashMap
supports O(1) get/put operations complexity time. LinkedHashMap
preserves the order of the inserted items.
TreeMap
supports O(log n) get/put operations complexity time. Since it has a mechanism to preserver natural order of the items using Comparable
or Comparator
.
Performance of TreeMap, HashMap and LinkedHashMap?
Use a HashMap
unless you have some need for ordering. HashMap
is faster.
That said, you can make it easy to switch by using the generic interface as your declaration:
Map<String,String> M = new HashMap<String,String>();
...use M lots of places...
Then all you have to do is switch one place and your code uses the new map type.
Edit:
A simple timing test:
import java.util.*;
class TimingTest {
public static void main(String[] args) {
Map<String,String> M = new HashMap<String,String>();
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
M.put(Integer.toString(i), "foo");
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
What is the difference between a HashMap and a TreeMap?
TreeMap
is an example of a SortedMap
, which means that the order of the keys can be sorted, and when iterating over the keys, you can expect that they will be in order.
HashMap
on the other hand, makes no such guarantee. Therefore, when iterating over the keys of a HashMap
, you can't be sure what order they will be in.
HashMap
will be more efficient in general, so use it whenever you don't care about the order of the keys.
difference between linkedhashmap, hashmap, map, hashtable
I doubt the differences can be explained significantly better than what's already written in the JavaDocs for these classes:
- Map is the basic interface common to all these classes
- a Hashtable is one implementation of that interface, for the "old" days when it was thought that having everything synchronized is a good idea (ref. Vector). It offers "kind of" thread-safety, if you know what you are doing. If you are serious about a map which can be used from multiple threads you should absolutely check out the
ConcurrentHashMap
andConcurrentSkipListMap
. - a HashMap is almost the same as a Hashtable, but with the synchronization removed. It's the preferred general-purpose Map implementation.
- a LinkedHashMap additionally maintains a linked list of it's entries, which allows to maintain an ordering or use it as a LRU cache easily, just read the JavaDoc.
All of the aforementioned Map
implementations have their basic get/put operations in (amortized) O(1) time complexity. There are minor differences in the handling of null
values, it's inevitable to check the JavaDoc for details.
To get an idea of how these classes are implemeted, have a look at their inheritance tree:
Map
(just the interface)Dictionary
(obsoleted abstract class)Hashtable
(the "old" map implementation lives on it's own)
AbstractMap
(the basic functionality of the "new" map implementations)HashMap
(the first concrete map implementation for general purpose use)LinkedHashMap
(extendsHashMap
by mainaining the linked list)
TreeMap or HashMap?
Hashtables (usually) perform search operations (look up) bounded within the complexity of O(n)<=T(n)<=O(1)
, with an average case complexity of O(1 + n/k)
; however, binary search trees, (BST's), perform search operations (lookup) bounded within the complexity of O(n)<=T(n)<=O(log_2(n))
, with an average case complexity of O(log_2(n))
. The implementation for each (and every) data structure should be known (by you), to understand the advantages, drawbacks, time complexity of operations, and code complexity.
For example, the number of entries in a hashtable often have some fixed number of entries (some part of which may not be filled at all) with lists of collisions. Trees, on the other hand, usually have two pointers (references) per node, but this can be more if the implementation allows more than two child nodes per node, and this allows the tree to grow as nodes are added, but may not allow duplicates. (The default implementation of a Java TreeMap does not allow for duplicates)
There are special cases to consider as well, for example, what if the number of elements in a particular data structure increases without bound or approaches the limit of an underlying part of the data structure? What about amortized operations that perform some rebalancing or cleanup operation?
For example, in a hashtable, when the number of elements in the table become sufficiently large, and arbitrary number of collisions can occur. On the other hand, trees usually require come re-balancing procedure after an insertion (or deletion).
So, if you have something like a cache (Ex. the number of elements in bounded, or size is known) then a hashtable is probably your best bet; however, if you have something more like a dictionary (Ex. populated once and looked up many times) then I'd use a tree.
This is only in the general case, however, (no information was given). You have to understand process that happen how they happen to make the right choice in deciding which data structure to use.
When I need a multi-map (ranged lookup) or sorted flattening of a collection, then it can't be a hashtable.
Should I use LinkedHashMap or TreeMap if I insert and access in order?
Use a TreeMap
. Not for any performance reasons, but because it can be assigned to SortedMap
(or NavigableMap
), and that communicates clearly your intent that the map has a defined order.
Related Topics
How to Get the Current Date and Time in Utc or Gmt in Java
Compare Two Objects With .Equals() and == Operator
Want Current Date and Time in "Dd/Mm/Yyyy Hh:Mm:Ss.Ss" Format
Spring Boot Configure and Use Two Data Sources
Semicolon At End of 'If' Statement
Which @Notnull Java Annotation Should I Use
How to Run a Java Program from the Command Line on Windows
Instantiating a Generic Class in Java
How Does Java Garbage Collection Work With Circular References
How to Format a Number in Java
How to Make a Deep Copy of an Object
Jtextfields on Top of Active Drawing on Jpanel, Threading Problems
What Do ^ and $ Mean in a Regular Expression
Java Process With Input/Output Stream
Display Java.Util.Date in a Specific Format
Should Java 8 Getters Return Optional Type