difference between linkedhashmap, hashmap, map, hashtable
I am preparing for software interviews and i am stuck with a question for days now.
I have not been able to figure out the difference between linkedhashmap, map, hashtable, hashmap present in the Java Collection API.
Do all of these have the same get and put complexities? I know that map is the interface class and hashmap, hashtable, linkedhashmap implement this interface. So does that mean that the inner implementation of these 3 classes is the same? How are they implemented in the collections api?
Thanks in Advance!!!
I doubt the differences can be explained significantly better than what's already written in the JavaDocs for these classes:
ConcurrentHashMap
and ConcurrentSkipListMap
. 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
(extends HashMap
by mainaining the linked list) They all honor the same contract, but there are some differences in the implementation:
Generally, the best practice is to use Map
as the type for variables, and then you instantiate an implementing type based on the needs of your code. HashMap
is generally preferred unless you need some ordering guarantees, in which case LinkedHashMap
or TreeMap
are good choices.
All 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 their compareTo() method (or an externally supplied Comparator). Additionally, it implements the SortedMap 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 ConcurrrentHashMap instead of Hashtable.
链接地址: http://www.djcxy.com/p/73624.html