HashMap, LinkedHashMap和TreeMap在Java中的区别是什么?
我在输出中没有看到任何不同,因为这三个都有keySet和values。什么是哈希表?
Map m1 = new HashMap();
m1.put("map", "HashMap");
m1.put("schildt", "java2");
m1.put("mathew", "Hyden");
m1.put("schildt", "java2s");
print(m1.keySet());
print(m1.values());
SortedMap sm = new TreeMap();
sm.put("map", "TreeMap");
sm.put("schildt", "java2");
sm.put("mathew", "Hyden");
sm.put("schildt", "java2s");
print(sm.keySet());
print(sm.values());
LinkedHashMap lm = new LinkedHashMap();
lm.put("map", "LinkedHashMap");
lm.put("schildt", "java2");
lm.put("mathew", "Hyden");
lm.put("schildt", "java2s");
print(lm.keySet());
print(lm.values());
虽然这里有很多很好的答案,但我想给出我自己的表,描述与Java 11绑定的各种Map实现。
我们可以在图表中看到这些差异:
HashMap is the general-purpose Map commonly used when you have no special needs.
LinkedHashMap extends HashMap, adding this behavior: Maintains an order, the order in which the entries were originally added. Altering the value for key-value entry does not alter its place in the order.
TreeMap too maintains an order, but uses either (a) the “natural” order, meaning the value of the compareTo method on the key objects defined on the Comparable interface, or (b) invokes a Comparator implementation you provide.
TreeMap implements both the SortedMap interface, and its successor, the NavigableMap interface.
NULLs: TreeMap does not allow a NULL as the key, while HashMap & LinkedHashMap do.
All three allow NULL as the value.
HashTable is legacy, from Java 1. Supplanted by the ConcurrentHashMap class. Quoting the Javadoc: ConcurrentHashMap obeys the same functional specification as Hashtable, and includes versions of methods corresponding to each method of Hashtable.
以下是HashMap和TreeMap之间的主要区别
HashMap does not maintain any order. In other words , HashMap does not provide any guarantee that the element inserted first will be printed first, where as Just like TreeSet , TreeMap elements are also sorted according to the natural ordering of its elements
Internal HashMap implementation use Hashing and TreeMap internally uses Red-Black tree implementation.
HashMap can store one null key and many null values.TreeMap can not contain null keys but may contain many null values.
HashMap take constant time performance for the basic operations like get and put i.e O(1).According to Oracle docs , TreeMap provides guaranteed log(n) time cost for the get and put method.
HashMap is much faster than TreeMap, as performance time of HashMap is constant against the log time TreeMap for most operations.
HashMap uses equals() method in comparison while TreeMap uses compareTo() method for maintaining ordering.
HashMap implements Map interface while TreeMap implements NavigableMap interface.