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());

这些是同一接口的不同实现。每种实现都有一些优点和缺点(快速插入,缓慢搜索),反之亦然。

有关详细信息,请参阅TreeMap, HashMap, LinkedHashMap的javadoc。


这三个都表示从唯一键到值的映射,因此实现了Map接口。

HashMap is a map based on hashing of the keys. It supports O(1) get/put operations. Keys must have consistent implementations of hashCode() and equals() for this to work. LinkedHashMap is very similar to HashMap, but it adds awareness to the order at which items are added (or accessed), so the iteration order is the same as insertion order (or access order, depending on construction parameters). TreeMap is a tree based mapping. Its put/get operations take O(log n) time. It requires items to have some comparison mechanism, either with Comparable or Comparator. The iteration order is determined by this mechanism.


这三个类都实现了Map接口,并提供了基本相同的功能。最重要的区别是迭代条目的顺序:

HashMap绝对不保证迭代顺序。当添加新元素时,它甚至可以(也将会)完全改变。 TreeMap将根据键的compareTo()方法(或外部提供的Comparator)的“自然顺序”进行迭代。此外,它实现了SortedMap接口,该接口包含依赖于此排序顺序的方法。 LinkedHashMap将按照条目放入映射的顺序进行迭代

“哈希表”是基于哈希的映射的通用名称。在Java API的上下文中, Hashtable是Java 1.1时代的一个过时的类,在集合框架存在之前。它不应该再使用了,因为它的API中充满了重复功能的过时方法,而且它的方法是同步的(这会降低性能,而且通常是无用的)。使用ConcurrentHashMap而不是Hashtable。


@Amit: SortedMap is an interface whereas TreeMap is a class which implements the SortedMap interface. That means if follows the protocol which SortedMap asks its implementers to do. A tree unless implemented as search tree, can't give you ordered data because tree can be any kind of tree. So to make TreeMap work like Sorted order, it implements SortedMap ( e.g, Binary Search Tree - BST, balanced BST like AVL and R-B Tree , even Ternary Search Tree - mostly used for iterative searches in ordered way ).

public class TreeMap<K,V>
extends AbstractMap<K,V>
implements SortedMap<K,V>, Cloneable, Serializable

在坚果壳 HashMap:给出O(1)的数据,没有排序

TreeMap:给出O(log N),以2为底的数据。使用有序键

LinkedHashMap:是具有链表(想想索引- skiplist)功能的哈希表,以插入树的方式存储数据。最适合实现LRU(最近最少使用)。


HashMap

它有一对值(键,值) 禁止复制键值 无序的无序 它允许一个空键和多个空值

哈希表

和哈希映射一样 它不允许空键和空值

LinkedHashMap

它是map实现的有序版本 基于链表和哈希数据结构

TreeMap

有序和排序版本 基于哈希数据结构


这是我自己使用地图的经验,关于我何时使用每种地图:

HashMap - Most useful when looking for a best-performance (fast) implementation. TreeMap (SortedMap interface) - Most useful when I'm concerned with being able to sort or iterate over the keys in a particular order that I define. LinkedHashMap - Combines advantages of guaranteed ordering from TreeMap without the increased cost of maintaining the TreeMap. (It is almost as fast as the HashMap). In particular, the LinkedHashMap also provides a great starting point for creating a Cache object by overriding the removeEldestEntry() method. This lets you create a Cache object that can expire data using some criteria that you define.


HashMap绝对不保证迭代顺序。它 当添加新元素时,甚至会完全改变。 TreeMap将根据键的“自然顺序”进行迭代 根据它们的compareTo()方法(或外部提供的 比较器)。此外,它实现了SortedMap接口, 其中包含依赖于此排序顺序的方法。LinkedHashMap 将按照条目放入映射中的顺序进行迭代

看看性能是如何变化的。

树映射是排序映射的实现。由于自然排序,put、get和containsKey操作的复杂度为O(log n)


我更喜欢视觉呈现:

Property HashMap TreeMap LinkedHashMap
Iteration Order no guaranteed order, will remain constant over time sorted according to the natural ordering insertion-order
Get / put / remove / containsKey O(1) O(log(n)) O(1)
Interfaces Map NavigableMap, Map, SortedMap Map
Null values/keys allowed only values allowed
Fail-fast behavior Fail-fast behavior of an iterator cannot be guaranteed, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification Fail-fast behavior of an iterator cannot be guaranteed, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification Fail-fast behavior of an iterator cannot be guaranteed, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification
Implementation buckets Red-Black Tree double-linked buckets
Is synchronized implementation is not synchronized implementation is not synchronized implementation is not synchronized

请看下图(大图)中每个类在类层次结构中的位置。TreeMap实现了SortedMap和NavigableMap,而HashMap没有。

HashTable已经过时,应该使用相应的ConcurrentHashMap类。


它们都提供一个key->值映射和一种遍历键的方法。最重要的区别 这些类是时间保证和键的顺序。

HashMap offers 0(1) lookup and insertion. If you iterate through the keys, though, the ordering of the keys is essentially arbitrary. It is implemented by an array of linked lists. TreeMap offers O(log N) lookup and insertion. Keys are ordered, so if you need to iterate through the keys in sorted order, you can. This means that keys must implement the Comparable interface.TreeMap is implemented by a Red-Black Tree. LinkedHashMap offers 0(1) lookup and insertion. Keys are ordered by their insertion order. It is implemented by doubly-linked buckets.

假设你将一个空的TreeMap, HashMap和LinkedHashMap传递给下面的函数:

void insertAndPrint(AbstractMap<Integer, String> map) {
  int[] array= {1, -1, 0};
  for (int x : array) {
    map.put(x, Integer.toString(x));
  }
  for (int k: map.keySet()) {
   System.out.print(k + ", ");
  }
}

它们的输出如下所示。

对于HashMap,在我自己的测试中,输出是{0,1,-1},但它可以是任何顺序。没有任何保证 排序。 Treemap,输出为{- 1,0,1} LinkedList,输出为{1,-1,0}


HashMap、TreeMap和LinkedHashMap这三个类都实现了java.util.Map接口,并表示从唯一键到值的映射。

HashMap

HashMap包含基于键的值。 它只包含独特的元素。 它可以有一个空键和多个空值。 它没有维持秩序。 公共类HashMap<K,V>扩展了AbstractMap<K,V>实现了Map<K,V>,可克隆,可序列化

LinkedHashMap

LinkedHashMap包含基于键的值。 它只包含独特的元素。 它可以有一个空键和多个空值。 它与HashMap相同,只是维护插入顺序。//见下面的减速等级 公共类LinkedHashMap<K,V>扩展HashMap<K,V>实现Map<K,V>

TreeMap

TreeMap包含基于键的值。它实现了NavigableMap接口并扩展了AbstractMap类。 它只包含独特的元素。 它不能有空键,但可以有多个空值。 它与HashMap相同,只是维护升序(使用键的自然顺序进行排序)。 公共类TreeMap<K,V>扩展AbstractMap<K,V>实现NavigableMap<K,V>,可克隆,可序列化

哈希表

哈希表是一个列表数组。每个列表都被称为一个桶。桶的位置通过调用hashcode()方法来标识。哈希表包含基于键的值。 它只包含独特的元素。 它可能没有任何空键或值。 它是同步的。 这是一个传承类。 公共类Hashtable<K,V>扩展Dictionary<K,V>实现Map<K,V>,可克隆,可序列化

裁判:http://javarevisited.blogspot.in/2015/08/difference-between-HashMap-vs-TreeMap-vs-LinkedHashMap-Java.html


HashMap 可以包含一个空键。

HashMap没有秩序。

TreeMap

TreeMap不能包含任何空键。

TreeMap保持升序。

LinkedHashMap

LinkedHashMap可用于维护插入顺序,即键被插入到Map中,也可用于维护访问顺序,即键被访问。

例子::

1) HashMap map = new HashMap();

    map.put(null, "Kamran");
    map.put(2, "Ali");
    map.put(5, "From");
    map.put(4, "Dir");`enter code here`
    map.put(3, "Lower");
    for (Map.Entry m : map.entrySet()) {
        System.out.println(m.getKey() + "  " + m.getValue());
    } 

2) TreeMap map = new TreeMap();

    map.put(1, "Kamran");
    map.put(2, "Ali");
    map.put(5, "From");
    map.put(4, "Dir");
    map.put(3, "Lower");
    for (Map.Entry m : map.entrySet()) {
        System.out.println(m.getKey() + "  " + m.getValue());
    }

3) LinkedHashMap map = new LinkedHashMap();

    map.put(1, "Kamran");
    map.put(2, "Ali");
    map.put(5, "From");
    map.put(4, "Dir");
    map.put(3, "Lower");
    for (Map.Entry m : map.entrySet()) {
        System.out.println(m.getKey() + "  " + m.getValue());
    }

哈希映射不保留插入顺序。 的例子。Hashmap 如果您正在插入键作为

1  3
5  9
4   6
7   15
3   10

它可以存储为

4  6
5  9
3  10
1  3
7  15

链接Hashmap保留插入顺序。

的例子。 如果您正在插入键

1  3
5  9
4   6
7   15
3   10

它将存储为

1  3
5  9
4   6
7   15
3   10

和我们插入的一样。

树映射以键的递增顺序存储山谷。 的例子。 如果您正在插入键

1  3
5  9
4   6
7   15
3   10

它将存储为

1  3
3  10
4   6
5   9
7   15

以下是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.


HashMap: 不维持秩序 比LinkedHashMap快 用于存储对象堆 LinkedHashMap: LinkedHashMap插入顺序将被维持 比HashMap慢,比TreeMap快 如果你想保持一个插入顺序,使用这个。 TreeMap: TreeMap是一种基于树的映射 TreeMap将遵循键的自然顺序 比HashMap和LinkedHashMap慢 在需要维护自然(默认)排序时使用TreeMap


三者中最重要的是如何保存条目的顺序。

HashMap -不保存条目的顺序。 如。

public static void main(String[] args){
        HashMap<String,Integer> hashMap = new HashMap<>();
        hashMap.put("First",1);// First ---> 1 is put first in the map
        hashMap.put("Second",2);//Second ---> 2 is put second in the map
        hashMap.put("Third",3); // Third--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : hashMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

LinkedHashMap:它保存条目的顺序。例如:

public static void main(String[] args){
        LinkedHashMap<String,Integer> linkedHashMap = new LinkedHashMap<>();
        linkedHashMap.put("First",1);// First ---> 1 is put first in the map
        linkedHashMap.put("Second",2);//Second ---> 2 is put second in the map
        linkedHashMap.put("Third",3); // Third--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : linkedHashMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }

TreeMap:按键的升序保存条目。例如:

public static void main(String[] args) throws IOException {
        TreeMap<String,Integer> treeMap = new TreeMap<>();
        treeMap.put("A",1);// A---> 1 is put first in the map
        treeMap.put("C",2);//C---> 2 is put second in the map
        treeMap.put("B",3); //B--->3 is put third in the map
        for(Map.Entry<String,Integer> entry : treeMap.entrySet())
        {
            System.out.println(entry.getKey()+"--->"+entry.getValue());
        }
    }


虽然这里有很多很好的答案,但我想给出我自己的表,描述与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.