Map Interface
java.util collection classes in Java contains some of the most commonly used classes. The most common type is the set of List and Map.
Map is a key - value pair (key-value) set, Map set each element contains a key object and a target value. Wherein, does not allow duplicate key object, and the value of the object may be repeated, and the value of the type of Map objects may also be , as elements of an array may also be the same array.
Its basic operations are: to add the key-value key "," Get key "," Get value "," size acquiring map "," empty map "key-value of the basic key operation.
The Map interface to a can not be instantiated, Map interface to achieve two main classes:. HashMap and TreeMap classes where classes, according to the HashMap class key to access the object hash algorithm, and the TreeMap class objects can be sorted key.
summary:
- Map provides a mapping relationship, which is the key element of (key-value) in the form of storage can be achieved quickly find value in accordance with key
- Map key object instance in the form of a large memory Entry type
- Key (key value) value can not be repeated --value
HashMap class
- HaskMap Map is an important implementation class, and it is most commonly used to achieve based on a hash table
- Entry object HashMap is randomly oriented
- Key value derived from the value that can be null, but a HashMap only one key is null mapping (key not duplicate)
HashMap relationship with the Map is shown:
从图中可以看出:
(01) HashMap继承于AbstractMap类,实现了Map接口。Map是"key-value键值对"接口,AbstractMap实现了"键值对"的通用函数接口。
(02) HashMap是通过"拉链法"实现的哈希表。它包括几个重要的成员变量:table, size, threshold, loadFactor, modCount。
table是一个Entry[]数组类型,而Entry实际上就是一个单向链表。哈希表的"key-value键值对"都是存储在Entry数组中的。
size是HashMap的大小,它是HashMap保存的键值对的数量。
threshold是HashMap的阈值,用于判断是否需要调整HashMap的容量。threshold的值="容量*加载因子",当HashMap中存储数据的数量达到threshold时,就需要将HashMap的容量加倍。
loadFactor就是加载因子。
modCount是用来实现fail-fast机制的。
类型区别
HashMap
最常用的Map,它根据键的HashCode 值存储数据,根据键可以直接获取它的值,具有很快的访问速度。HashMap最多只允许一条记录的键为Null(多条会覆盖);允许多条记录的值为 Null。非同步的。它是基于“拉链法”实现的散列表。一般用于单线程程序中。
TreeMap
能够把它保存的记录根据键(key)排序,默认是按升序排序,也可以指定排序的比较器,当用Iterator 遍历TreeMap时,得到的记录是排过序的。TreeMap不允许key的值为null。非同步的。 它是通过红黑树实现的。它一般用于单线程中存储有序的映射。
Hashtable
与 HashMap类似,不同的是: key和value的值均不允许为null;它支持线程的同步,即任一时刻只有一个线程能写Hashtable,因此也导致了Hashtale在写入时会比较慢。 它是基于“拉链法”实现的散列表。它一般用于多线程程序中。
LinkedHashMap
保存了记录的插入顺序,在用Iterator遍历LinkedHashMap时,先得到的记录肯定是先插入的.在遍历的时候会比HashMap慢。key和value均允许为空,非同步的。
参考与推荐:
1、https://www.cnblogs.com/chengxiao/p/6059914.html
2、https://www.cnblogs.com/skywang12345/p/3311126.html
3、https://www.cnblogs.com/lzq198754/p/5780165.html
4、https://www.cnblogs.com/skywang12345/p/3310835.html