Map分析
来源:互联网 发布:终极斗士 知乎 编辑:程序博客网 时间:2024/06/10 14:11
java.util.Map
1.Map接口和方法
1.1覆盖了equal()和hashCode()
|方法|说明|
|
|equal(Obejct o)|根据实际比较指定对象与Map的等价性|
|hashCode()|返回次Map的哈希表|
1.2Map的主要增减删除方法
|方法|说明|
|
|clear()|删除所有映射|
|remove(object)|删除指定的的key-value|
|put(Object key,Obejct value)|增加新的键值对|
|putAll(Map t)|把参数Map中的所有键值对全部复制到本Map|
|get(Object key)|返回指定key对应的value,如果没有加返回null|
|size)|返回键值对的个数|
1.3返回元素集合的方法
|方法|说明|
|
|entrySet()|返回此映射中包含的映射关系的 Set 视图|
|keySet()|返回此映射中包含的键的 Set 视图|
|values()|返回此映射中包含的值的 Collection 视图|
前面两个返回的是Set对象,第三个返回的是Collection对象,这里拿到的是基础Map的视图(在这里删除了Set中也没有了---测试不是这样的,看了源码再改)
1.4负载因子
如果(负载因子)x(容量)>(Map 大小),则调整 Map 大小
|负载因子大小|影响|
|
|大|对空间的利用更加充分,查找的效率会降低|
|小|散列表过于稀疏,对空间造成严重的浪费|
负载因子本身是空间和时间之间的调整折衷。较小的负载因子将占用更多的空间,但将降低冲突的可能性,从而将加快访问和更新的速度。使用大于 0.75 的负载因子可能是不明智的,而使用大于 1.0 的负载因子肯定是不明知的,这是因为这必定会引发一次冲突。使用小于 0.50 的负载因子好处并不大,但只要您有效地调整 Map 的大小,应不会对小负载因子造成性能开销,而只会造成内存开销。但较小的负载因子将意味着如果您未预先调整 Map 的大小,则导致更频繁的调整大小,从而降低性能,因此在调整负载因子时一定要注意这个问题。
2 Map
<!--lang: java-->public interface Map<K,V> { //抽象方法 int size(); boolean isEmpty(); boolean containsKey(Object key); boolean containsValue(Object value); V get(Object key); V put(K key, V value); V remove(Object key); void putAll(Map<? extends K, ? extends V> m); void clear(); Set<K> keySet(); Collection<V> values(); Set<Map.Entry<K, V>> entrySet(); boolean equals(Object o); int hashCode();//内部接口interface Entry<K,V> { K getKey(); V getValue(); V setValue(V value); boolean equals(Object o); int hashCode(); ...}//包含key并且返回value不为null就返回value,否则返回默认值default V getOrDefault(Object key, V defaultValue) { V v; return (((v = get(key)) != null) || containsKey(key)) ? v : defaultValue;}//如果不存在key-value就插入,负责返回已存在的key的value default V putIfAbsent(K key, V value) { V v = get(key); if (v == null) { v = put(key, value); } return v;}//如果key对应的value存在并且等于传入的value就删除这对键值对//或者传入的key-value本身就不存在default boolean remove(Object key, Object value) { Object curValue = get(key); if (!Objects.equals(curValue, value) || (curValue == null && !containsKey(key))) { return false; } remove(key); return true;}//出入新的键值对,第二个参数保证key-oldValue存在default boolean replace(K key, V oldValue, V newValue) { Object curValue = get(key); if (!Objects.equals(curValue, oldValue) || (curValue == null && !containsKey(key))) { return false; } put(key, newValue); return true;} //替换前面存在的key-value,返回前面的value值default V replace(K key, V value) { V curValue; if (((curValue = get(key)) != null) || containsKey(key)) { curValue = put(key, value); } return curValue;}}
3.HashMap
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable { private static final long serialVersionUID = 362498820763181265L; static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; static final int MAXIMUM_CAPACITY = 1 << 30; static final float DEFAULT_LOAD_FACTOR = 0.75f; //load factor 负载因子 //Map.Entry------------------------ static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; V value; Node<K,V> next; Node(int hash, K key, V value, Node<K,V> next) { this.hash = hash; this.key = key; this.value = value; this.next = next; } public final K getKey() { return key; } public final V getValue() { return value; } public final String toString() { return key + "=" + value; } public final int hashCode() { return Objects.hashCode(key) ^ Objects.hashCode(value); } public final V setValue(V newValue) { V oldValue = value; value = newValue; return oldValue; } public final boolean equals(Object o) { if (o == this) return true; if (o instanceof Map.Entry) { Map.Entry<?,?> e = (Map.Entry<?,?>)o; if (Objects.equals(key, e.getKey()) && Objects.equals(value, e.getValue())) return true; } return false; } } //成员变量 transient Node<K,V>[] table; transient Set<Map.Entry<K,V>> entrySet; transient int size; transient int modCount; int threshold; final float loadFactor; //构造方法 public HashMap() { this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted } public HashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR); } public HashMap(int initialCapacity, float loadFactor) { //参数判断,抛异常 if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; //函数调用见下面 this.threshold = tableSizeFor(initialCapacity); } static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;}public HashMap(Map<? extends K, ? extends V> m) { this.loadFactor = DEFAULT_LOAD_FACTOR; putMapEntries(m, false);}//方法public int size() { return size;}public boolean isEmpty() { return size == 0;}//--------------getpublic V get(Object key) { Node<K,V> e; //调用了 hash() getNode() return (e = getNode(hash(key), key)) == null ? null : e.value;}static final int hash(Object key) { int h; //h如果大于65535则产一个新的值,否则全部就是key.hashCode(); return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);}//参数1是hash(key),2是keyfinal Node<K,V> getNode(int hash, Object key) { Node<K,V>[] tab; Node<K,V> first, e; int n; K k; if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) { //first的得出因为在put时就采用了这样算法 if (first.hash == hash && // always check first node ((k = first.key) == key || (key != null && key.equals(k)))) //如果链表第一个就是要求的,直接返回 return first; if ((e = first.next) != null) { if (first instanceof TreeNode) return ((TreeNode<K,V>)first).getTreeNode(hash, key); do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) return e; } while ((e = e.next) != null); //循环遍历链表 } } return null;}//因为在上面的getNode()函数中,当包含这个key-value是返回Node否则返回nullpublic boolean containsKey(Object key) { return getNode(hash(key), key) != null;}//---------------putpublic V put(K key, V value) { return putVal(hash(key), key, value, false, true);}/** * Implements Map.put and related methods * * @param hash hash for key * @param key the key * @param value the value to put * @param onlyIfAbsent if true, don't change existing value * @param evict if false, the table is in creation mode. * @return previous value, or null if none */final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> p; int n, i; //第一次进入这里进行resize(); if ((tab = table) == null || (n = tab.length) == 0) n = (tab = resize()).length; //tab[i = (n - 1) & hash]存在数组这个位置上面去 if ((p = tab[i = (n - 1) & hash]) == null)//上面没有数据,直接加到链表第一个 tab[i] = newNode(hash, key, value, null); else {//往链表后面追加 Node<K,V> e; K k; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))//第一个位置key-value本身存在 e = p; else if (p instanceof TreeNode) e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash, key, value, null);//插入链表尾部 if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st treeifyBin(tab, hash); break; } if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))//后面位置key-value本身存在 break; p = e; } } if (e != null) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e);//do nothing return oldValue; } } ++modCount; //仅仅在修改了已存在的key-value才会执行到这一步 if (++size > threshold) resize(); afterNodeInsertion(evict);//do nothing return null;}Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) { return new Node<>(hash, key, value, next);}//------------removepublic V remove(Object key) { Node<K,V> e; return (e = removeNode(hash(key), key, null, false, true)) == null ? null : e.value;} final Node<K,V> removeNode(int hash, Object key, Object value, boolean matchValue, boolean movable) { Node<K,V>[] tab; Node<K,V> p; int n, index; if ((tab = table) != null && (n = tab.length) > 0 && (p = tab[index = (n - 1) & hash]) != null) { //找到数组的下标 Node<K,V> node = null, e; K k; V v; if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k)))) //首结点就是 node = p; else if ((e = p.next) != null) { //循环链表查找要删除的key-value if (p instanceof TreeNode) node = ((TreeNode<K,V>)p).getTreeNode(hash, key); else { do { if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) { node = e; break; } p = e; } while ((e = e.next) != null); } } if (node != null && (!matchValue || (v = node.value) == value || (value != null && value.equals(v)))) { //找到node并检车value就会最终返回一个node if (node instanceof TreeNode) ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable); else if (node == p)//如何使首结点,直接指向下一个就好了 tab[index] = node.next; else //中间节点 p.next = node.next; ++modCount; --size; afterNodeRemoval(node); return node; } } return null;}//清空public void clear() { Node<K,V>[] tab; modCount++; if ((tab = table) != null && size > 0) { size = 0; for (int i = 0; i < tab.length; ++i) tab[i] = null; //付个空指针就好了 }}public boolean containsValue(Object value) { Node<K,V>[] tab; V v; if ((tab = table) != null && size > 0) { for (int i = 0; i < tab.length; ++i) { //遍历数组 for (Node<K,V> e = tab[i]; e != null; e = e.next) { //遍历链表 if ((v = e.value) == value || (value != null && value.equals(v))) return true; } } } return false;}//set ----------- collectionspublic Set<K> keySet() { Set<K> ks = keySet; if (ks == null) { ks = new KeySet(); keySet = ks; } return ks;} public Collection<V> values() { Collection<V> vs = values; if (vs == null) { vs = new Values(); values = vs; } return vs;}public Set<Map.Entry<K,V>> entrySet() { Set<Map.Entry<K,V>> es; return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;}//这个内部类中的成员基本上全部是外部类的final class KeySet extends AbstractSet<K> { public final int size() { return size; } public final void clear() { HashMap.this.clear(); //调用这个clear就相当于这届调用HashMap.clear();} public final Iterator<K> iterator() { return new KeyIterator(); } public final boolean contains(Object o) { return containsKey(o); } public final boolean remove(Object key) { return removeNode(hash(key), key, null, false, true) != null; } public final Spliterator<K> spliterator() { return new KeySpliterator<>(HashMap.this, 0, -1, 0, 0); } public final void forEach(Consumer<? super K> action) { Node<K,V>[] tab; if (action == null) throw new NullPointerException(); if (size > 0 && (tab = table) != null) { int mc = modCount; for (int i = 0; i < tab.length; ++i) { for (Node<K,V> e = tab[i]; e != null; e = e.next) action.accept(e.key); } if (modCount != mc) throw new ConcurrentModificationException(); } }}/* ------------------------------------------------------------ */// iteratorsabstract class HashIterator { Node<K,V> next; // next entry to return Node<K,V> current; // current entry int expectedModCount; // for fast-fail int index; // current slot HashIterator() { expectedModCount = modCount; Node<K,V>[] t = table; current = next = null; index = 0; if (t != null && size > 0) { // advance to first entry do {} while (index < t.length && (next = t[index++]) == null); //next指向第一个非Null的 } } public final boolean hasNext() { //下一个元素是否存在 return next != null; } final Node<K,V> nextNode() { Node<K,V>[] t; Node<K,V> e = next; if (modCount != expectedModCount) throw new ConcurrentModificationException(); if (e == null) //没有了 throw new NoSuchElementException(); if ((next = (current = e).next) == null && (t = table) != null) { //下一个为null是一直循环直到找到不为Null的下次备用 do {} while (index < t.length && (next = t[index++]) == null); } return e; } public final void remove() { Node<K,V> p = current; if (p == null) throw new IllegalStateException(); if (modCount != expectedModCount) throw new ConcurrentModificationException(); current = null; K key = p.key; removeNode(hash(key), key, null, false, false); expectedModCount = modCount; }}//下面3个都是调用了nextNode()final class KeyIterator extends HashIterator implements Iterator<K> { public final K next() { return nextNode().key; }}final class ValueIterator extends HashIterator implements Iterator<V> { public final V next() { return nextNode().value; }}final class EntryIterator extends HashIterator implements Iterator<Map.Entry<K,V>> { public final Map.Entry<K,V> next() { return nextNode(); }}}
- Map分析
- Java容器分析--Map
- Google Map分析(1)
- Java容器分析--Map
- Map Editor 制作分析
- system.map文件分析
- Bit-map算法分析
- map reduce原理分析
- std::map源码分析
- Map架构分析
- KEIL MAP文件分析
- Java容器分析--Map
- Java容器分析--Map
- Map 遍历分析
- Map--HashMap实现分析
- IAR map文件分析
- Map接口源码分析
- KEIL MAP文件分析
- 快速幂算法
- Zookeeper的单机模式与伪分布式模式的搭建
- 设计模式之单例模式
- 《简明python教程》的学习笔记
- Redis Cluster 3.0.5 集群实战
- Map分析
- 设计原则(二)
- Ubuntu使用中的一些问题
- CSS基础(六):浮动深入
- 初学者如何从零学习人工智能?看完你就懂了
- 移动端 ionic angularjs列表和单选以及多选框混合使用问题
- Android 自定义View之随机生成图片验证码
- 在使用第三方的SDk 的时候我们一般都会需要添jar和so
- 数据存储全方案,详解持久化技术