三、Map
先来讲一下Map,Map和Collection完全不是一个系列的,按理说讲完Collection的List,应该接着讲Collection的Set,但是因为Set中很多实现是基于Map来实现的,所以将Map提前。Map是一个接口,存储内容是键值对key-value,不能包含重复的键。
1.HashMap
AbstractMap是实现Map的抽象类,HashMap继承于AbstractMap。
Map的API:(JDK1.8版本新增较多,为25个详见 https://docs.oracle.com/javase/8/docs/api/index.html)
abstract void clear() abstract boolean containsKey(Object key) abstract boolean containsValue(Object value) abstract Set<Entry<K, V>> entrySet() abstract boolean equals(Object object) abstract V get(Object key) abstract int hashCode() abstract boolean isEmpty() abstract Set<K> keySet() abstract V put(K key, V value) abstract void putAll(Map<? extends K, ? extends V> map) abstract V remove(Object key) abstract int size() abstract Collection<V> values()
AbstractMap的API只比Map新增了两个方法,不妨:
String toString() Object clone()
Map.Entry是Map类的静态接口,其API为 :
abstract boolean equals(Object object) abstract K getKey() abstract V getValue() abstract int hashCode() abstract V setValue(V object)
HashMap是线程不安全的,其key和value都可以是null。此外,HashMap不是有序的映射(什么是有序? 2019.1.1补:遍历的顺序和插入的顺序无直接关系)。
(1)HashMap存储情况
众所周知,哈希冲突的时候最经典的处理方法有再哈希和
基本成员域有:
/**
* The table, initialized on first use, and resized as
* necessary. When allocated, length is always a power of two.
* (We also tolerate length zero in some operations to allow
* bootstrapping mechanics that are currently not needed.)
*/
transient Node<K,V>[] table;
/**
* Holds cached entrySet(). Note that AbstractMap fields are used
* for keySet() and values().
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* The number of key-value mappings contained in this map.
*/
transient int size;
/**
* The number of times this HashMap has been structurally modified
* Structural modifications are those that change the number of mappings in
* the HashMap or otherwise modify its internal structure (e.g.,
* rehash). This field is used to make iterators on Collection-views of
* the HashMap fail-fast. (See ConcurrentModificationException).
*/
transient int modCount;
/**
* The next size value at which to resize (capacity * load factor).
*
* @serial
*/
// (The javadoc description is true upon serialization.
// Additionally, if the table array has not been allocated, this
// field holds the initial array capacity, or zero signifying
// DEFAULT_INITIAL_CAPACITY.)
int threshold;
/**
* The load factor for the hash table.
*
* @serial
*/
final float loadFactor;
size是键值对的个数,loadfactor称为装载因子,其作用是为了使哈希中的存储更加均匀,减小冲突,定义如下:
loadfactor=元素个数/哈希表容量
HashMap共有四种构造函数:
public HashMap()
public HashMap(int initialCapacity)
public HashMap(int initialCapacity,float loadFactor)
public HashMap(Map<? extends K,? extends V> m)
SortedMap是排序键值对的接口,实现排序的的方法是Comparator。而NavigableMap接口继承于SortedMap,新增了一些导航方法。