java集合中Map接口的实现类有HashMap、Hashtable、LinkedHashMap和TreeMap,与List不同的是Map并不是继承自Collection接口。可以这样来理解它:

  • Map提供key到value的映射,一个Map中不能包含相同的key,每个key只能映射一个 value。
  • Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射

 1.HashMap

  • HashMap的基本实现为一个链表数组(Entry<K, V>[ ]),即存放链表的数组,数组中的每个元素都是一个链表的头结点,而链表中的基本数据类型是一个静态内部类(Node)的对象,这些对象都具有相同的hash(key)值,所以是一种无序存储
 1     static class Node<K,V> implements Map.Entry<K,V> {
 2         final int hash;
 3         final K key;
 4         V value;
 5         Node<K,V> next;
 6 
 7         Node(int hash, K key, V value, Node<K,V> next) {
 8             this.hash = hash;
 9             this.key = key;
10             this.value = value;
11             this.next = next;
12         }
13 
14         public final K getKey()        { return key; }
15         public final V getValue()      { return value; }
16         public final String toString() { return key + "=" + value; }
17 
18         public final int hashCode() {
19             return Objects.hashCode(key) ^ Objects.hashCode(value);
20         }
21 
22         public final V setValue(V newValue) {
23             V oldValue = value;
24             value = newValue;
25             return oldValue;
26         }
27 
28         public final boolean equals(Object o) {
29             if (o == this)
30                 return true;
31             if (o instanceof Map.Entry) {
32                 Map.Entry<?,?> e = (Map.Entry<?,?>)o;
33                 if (Objects.equals(key, e.getKey()) &&
34                     Objects.equals(value, e.getValue()))
35                     return true;
36             }
37             return false;
38         }
39     }
View Code

相关文章: