Map

本文主要介绍Map接口以及其主要实现类:HashMap、LinkedHashMap、TreeMap、Hashtable、Properties,其中包括HashMap、TreeMap的底层实现原理。

Map的遍历方式

方式一,这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

方式二,在for-each循环中遍历keys或values(据说该方法比entrySet遍历在性能上稍好(快了10%),我还没有测试过):

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//遍历map中的键
for (Integer key : map.keySet()) {System.out.println("Key = " + key);
}
//遍历map中的值
for (Integer value : map.values()) {System.out.println("Value = " + value);
}

方式三,使用迭代器遍历(该种方式看起来冗余却有其优点所在。首先,在老版本java中这是惟一遍历map的方式。另一个好处是,你可以在遍历时调用iterator.remove()来删除entries,另两个方法则不能。):

// 不使用泛型
Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {Map.Entry entry = (Map.Entry) entries.next();Integer key = (Integer)entry.getKey();Integer value = (Integer)entry.getValue();System.out.println("Key = " + key + ", Value = " + value);
}
// 使用泛型
Map<Integer, Integer> map = new HashMap<>();
Iterator<Map.Entry<Integer, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()){Map.Entry<Integer, Integer> next = iterator.next();System.out.println(next);
}

方式四,通过键找值遍历(循环中通过key来拿到value效率低):

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {Integer value = map.get(key);System.out.println("Key = " + key + ", Value = " + value);
}

HashMap

HashMap初始化:

static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;
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);
}
public HashMap(int initialCapacity) {this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
public HashMap() {this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
public HashMap(Map<? extends K, ? extends V> m) {this.loadFactor = DEFAULT_LOAD_FACTOR;putMapEntries(m, false);
}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;
}

显然,在初始化时如果没有传入Map的大小,则只是改了下了一个加载因子;而在传入initialCapacity时则会计算出threshold(临界值),用于判断是否进行扩容。然后在使用put()的时候才会真正创建hashTable:

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/*** Associates the specified value with the specified key in this map.* If the map previously contained a mapping for the key, the old* value is replaced.** @param key key with which the specified value is to be associated* @param value value to be associated with the specified key* @return the previous value associated with <tt>key</tt>, or*         <tt>null</tt> if there was no mapping for <tt>key</tt>.*         (A <tt>null</tt> return can also indicate that the map*         previously associated <tt>null</tt> with <tt>key</tt>.)*/
public 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;if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;if ((p = tab[i = (n - 1) & hash]) == null)tab[i] = newNode(hash, key, value, null);else {Node<K,V> e; K k;// 此时p == tab[i = (n - 1) & hash]if (p.hash == hash &&((k = p.key) == key || (key != null && key.equals(k))))e = p;else if (p instanceof TreeNode)// 向红黑树中插入结点e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);else {for (int binCount = 0; ; ++binCount) { //没有终止条件的循环用于查看该索引上所有的node结点if ((e = p.next) == null) { //下一个为空时新建一个结点p.next = newNode(hash, key, value, null);if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1sttreeifyBin(tab, hash);break;}if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))// 此时需要进行替换valuebreak;p = e;}}if (e != null) { // existing mapping for key,key的hash值发生冲突V oldValue = e.value;// key的hash发生冲突后必然会进行一次替换(onlyIfAbsent默认为false)if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;if (++size > threshold)resize();afterNodeInsertion(evict);return null;
}
/*** Initializes or doubles table size.  If null, allocates in* accord with initial capacity target held in field threshold.* Otherwise, because we are using power-of-two expansion, the* elements from each bin must either stay at same index, or move* with a power of two offset in the new table.** @return the table*/
final Node<K,V>[] resize() {Node<K,V>[] oldTab = table;int oldCap = (oldTab == null) ? 0 : oldTab.length;int oldThr = threshold;int newCap, newThr = 0;if (oldCap > 0) {if (oldCap >= MAXIMUM_CAPACITY) {threshold = Integer.MAX_VALUE;return oldTab;}else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&oldCap >= DEFAULT_INITIAL_CAPACITY)newThr = oldThr << 1; // double threshold}else if (oldThr > 0) // initial capacity was placed in thresholdnewCap = oldThr;else {               // zero initial threshold signifies using defaultsnewCap = DEFAULT_INITIAL_CAPACITY; //默认16newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 默认0.75*16 = 12}if (newThr == 0) {float ft = (float)newCap * loadFactor;newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?(int)ft : Integer.MAX_VALUE);}threshold = newThr;@SuppressWarnings({"rawtypes","unchecked"})Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];table = newTab;if (oldTab != null) {for (int j = 0; j < oldCap; ++j) {Node<K,V> e;if ((e = oldTab[j]) != null) {oldTab[j] = null;if (e.next == null)newTab[e.hash & (newCap - 1)] = e;else if (e instanceof TreeNode)((TreeNode<K,V>)e).split(this, newTab, j, oldCap);else { // preserve orderNode<K,V> loHead = null, loTail = null;Node<K,V> hiHead = null, hiTail = null;Node<K,V> next;do {next = e.next;if ((e.hash & oldCap) == 0) {if (loTail == null)loHead = e;elseloTail.next = e;loTail = e;}else {if (hiTail == null)hiHead = e;elsehiTail.next = e;hiTail = e;}} while ((e = next) != null);if (loTail != null) {loTail.next = null;newTab[j] = loHead;}if (hiTail != null) {hiTail.next = null;newTab[j + oldCap] = hiHead;}}}}}return newTab;
}

从上面的代码以及部分我自己标注的中文注释可以看到:默认是创建了一个长度为16的表(Node<K,V>[])new Node[newCap];其临界值threshold为12。在后面每次调用put操作时也是调用上面三个方法。
当然,上面的代码也是可以看出,put首先调用key1所在类的hashCode()计算key1的哈希值,过程如下:

static final int hash(Object key) {int h;return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

此哈希值经过i = ((tab = resize()).length - 1) & hash后获得插入到哈希数组中的index,在put过程中会有如下情况:

  1. 如果此位置的数据为空,此时的key1-value1添加成功。
  2. 如果此位置的数据不为空,(意味这此位置有一个或者多个数据存在),比较key1和已经存在数据的哈希值:
    1. 如果key1的哈希值与已经存在的数据的哈希值都不相同,此时key1-value1添加到第一个位置,后续为原来的链表数据。
    2. 如果key1的哈希值与已经存在的的某个数据(key2-value2)的hash值相同,继续比较;调用key对象的equals()方法,
      1. 如果equals()返回false:,此时key1-value1添加到第一个位置,后续为原来的链表数据。
      2. 如果equals()返回true:此时使用value1替换value2并返回value2
        具体比较代码如下:
      if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
      

当然,在这里还是得说下jdk1.8相较与jdk1.7在底层实现方面还是的一些不同:

  1. 初始化时jdk1.7时直接创建了一个长度为16的数组,而1.8没有。
  2. jdk1.8底层的数组时Node[]而非Entry[],当他们实际是差不多的。
  3. jdk1.8是在首次调用put()方法的时候创建数组。
  4. jdk1.7的底层结构只有数组+链表;jdk1.8的底层结构为数组+链表+红黑树
    当数组的某一个索引位置上的元素以链表的形式存在的数据个数>8且当前数组的长度>64时,此时此索引位置上的所有数据改为使用红黑树存储。

LinkedHashMap

LinkedHashMap初始化:

public class LinkedHashMap<K,V>extends HashMap<K,V>implements Map<K,V>
{public LinkedHashMap(int initialCapacity, float loadFactor) {super(initialCapacity, loadFactor);accessOrder = false;}public LinkedHashMap(int initialCapacity) {super(initialCapacity);accessOrder = false;}public LinkedHashMap() {super();accessOrder = false;}public LinkedHashMap(Map<? extends K, ? extends V> m) {super();accessOrder = false;putMapEntries(m, false);}public LinkedHashMap(int initialCapacity,float loadFactor,boolean accessOrder) {super(initialCapacity, loadFactor);this.accessOrder = accessOrder;}
}

在初始化的过程中,我们发现LinkedHashMap就是HashMap,那么它和HashMap有什么区别呢,我们还是得看它的put()方法,然后在LinkedHashMap中却没有找到put()方法,这个时候怎么办呢?看它的父类,查看父类中的put()方法:

public V put(K key, V value) {return putVal(hash(key), key, value, false, true);
}

发现还是得找putVal方法,于是接着看:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,boolean evict) {Node<K,V>[] tab; Node<K,V> p; int n, i;if ((tab = table) == null || (n = tab.length) == 0)n = (tab = resize()).length;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))))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 1sttreeifyBin(tab, hash);break;}if (e.hash == hash &&((k = e.key) == key || (key != null && key.equals(k))))break;p = e;}}if (e != null) { // existing mapping for keyV oldValue = e.value;if (!onlyIfAbsent || oldValue == null)e.value = value;afterNodeAccess(e);return oldValue;}}++modCount;if (++size > threshold)resize();afterNodeInsertion(evict);return null;
}

初始化的过程中我们必定java必定会执行:tab[i] = newNode(hash, key, value, null);这句代码,于是去看newNode,点进去,发现HashMap中的newNode方法是这样子的:

Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {return new Node<>(hash, key, value, next);
}

那LinkedHashMap怎么和HashMap一样啊,这个时候就该思考,会不会是子类中还有什么是我们没有看到的,接着看子类LinkedHashMap,发现LinkedHashMap中也有newNode方法,原来是重写了:

Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {LinkedHashMap.Entry<K,V> p =new LinkedHashMap.Entry<K,V>(hash, key, value, e);linkNodeLast(p);return p;
}

再接着点进Entry看看是什么东西:

static class Entry<K,V> extends HashMap.Node<K,V> {Entry<K,V> before, after;Entry(int hash, K key, V value, Node<K,V> next) {super(hash, key, value, next);}
}

哦,原来它生成了一个和HashMap一样的结点,还在Entry<K,V> before, after;这里使用了before和after去记录生成的结点的前后顺序。

TreeMap

A Red-Black tree based NavigableMap implementation. The map is sorted according to the Comparable natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

上面这段话是java官方给出的说明,显然,TreeMap底层就是使用红黑树来实现的,并且是一个可以排序的Map,其中既可以使用自然排序,也可以是使用Comparator比较器来进行排序。
自然排序:

@Test
public void test9(){Map<Integer, Object> map = new TreeMap<>();map.put(11, "dasd");map.put(-1, "dasda");map.put(22, "dasd");map.put(33, "dasd");map.put(44, "dasd");map.put(44, "dad");Iterator<Map.Entry<Integer, Object>> iterator = map.entrySet().iterator();while (iterator.hasNext()){Map.Entry<Integer, Object> next = iterator.next();System.out.println(next);}/*** 打印结果:* -1=dasda* 11=dasd* 22=dasd* 33=dasd* 44=dad*/
}

Comparetor比较器排序:

@Test
public void test10(){Map<Employee, Object> map = new TreeMap<>();for(int i = 5; i > 0; i--){map.put(new Employee("test"+i, i, i), "dasd");}Iterator<Map.Entry<Employee, Object>> iterator = map.entrySet().iterator();while (iterator.hasNext()){Map.Entry<Employee, Object> next = iterator.next();System.out.println(next);}/*** 打印结果:* Employee{name='test1', age=1, salary=1}=dasd* Employee{name='test2', age=2, salary=2}=dasd* Employee{name='test3', age=3, salary=3}=dasd* Employee{name='test4', age=4, salary=4}=dasd* Employee{name='test5', age=5, salary=5}=dasd*/
}

Properties

Properties是HashMap的重要应用,利用了HashMap通过key查找迅速的特点,将这一特点用在了读取配置文件上,具体的使用如下:
在项目的资源文件夹下新建test.properties文件:

name=1baidu

测试代码:

@Test
public void test1() throws Exception{Properties properties = new Properties();FileInputStream fileInputStream= new FileInputStream("test.properties");properties.load(fileInputStream);System.out.println("name="+properties.getProperty("name"));/*** 打印结果:* name=1baidu*/
}

Java Map以及HashMap、TreeMap、HashTable相关推荐

  1. Map集合HashMap TreeMap的输出方法

    Map集合HashMap TreeMap的输出方法     [尊重原创,转载请注明出处]http://blog.csdn.net/guyuealian/article/details/51934301 ...

  2. 【Java集合之Map】HashMap、HashTable、TreeMap、LinkedHashMap区别

    Java为数据结构中的映射定义了一个接口java.util.Map,它有四个实现类,分别是HashMap.HashTable.LinkedHashMap和TreeMap.本节实例主要介绍这4中实例的用 ...

  3. java hashmap api_JAVA基础学习-集合三-Map、HashMap,TreeMap与常用API

    一.Map简述 1.1.简述 public interface Map 类型参数:K - 此映射所维护的键的类型 keyV - 映射值的类型 value该集合提供键--值的映射.key不能重复,一对对 ...

  4. Java中的HashMap和HashTable到底哪不同?(原文参考来自码农网)

    HashMap和HashTable有什么不同?在面试和被面试的过程中,我问过也被问过这个问题,也见过了不少回答,今天决定写一写自己心目中的理想答案. 代码版本 JDK每一版本都在改进.本文讨论的Has ...

  5. Java——集合(HashMap与Hashtable的区别)

    * HashMap和Hashtable的区别* 共同点:* 底层都是哈希算法,都是双列集合* 区别:* 1,HashMap是线程不安全的,效率高* Hashtable是线程安全的,效率低 * 2,Ha ...

  6. Java中的HashMap和HashTable到底哪不同?

    HashMap和HashTable有什么不同?在面试和被面试的过程中,我问过也被问过这个问题,也见过了不少回答,今天决定写一写自己心目中的理想答案. 代码版本 JDK每一版本都在改进.本文讨论的Has ...

  7. Java中的HashMap和Hashtable有什么区别?

    Java中的aHashMap和a有什么区别Hashtable? Java中的aHashMap和a有什么区别Hashtable? Java中的aHashMap和a有什么区别Hashtable? Java ...

  8. (三)Java中的HashMap与HashTable的区别

    首先,从JDK源码来看,HashMap和HashTable都实现了Map接口: 可以看出,HashTable是从JDK1.0就有的,HashMap而是从JDK1.2才有的. 二者实现的接口一致. 因此 ...

  9. Java Map(hashmap)

    目录 为什么使用集合框架? hashmap Hash: hashmap的扩容机制 其他 Map 中的"?"是什么意思? 为什么要尽量避免数组扩容 通过迭代器访问 hashmap中的 ...

最新文章

  1. 【转】CPU位数、核数、个数
  2. Lync 2013 与 Elastix 2.40 语音通信设置全过程(3)
  3. 第1章列表处理——1.1 Lisp列表
  4. 通过 OLE 上传资料
  5. 通过ClassLoader加载硬盘上的图片到内存及ImageIO的使用
  6. 真的了解js生成随机数吗
  7. 文献记录(part30)--DCR Disentangled component representation for sketch generation
  8. 如何用 J-Link 来串口调试?
  9. chrome gwt1.7_快速提示:使用Chrome开发工具调试GWT应用程序
  10. 观察者模式与Boost.Signals
  11. 企业靠一套数据平台实现“低成本运营战略”,降低成本600万
  12. cmake 配置生成后事件_cmake 管理debug release
  13. PAT甲级1005 字符串的处理
  14. vscode更改配置文件路径_VsCode的jsconfig配置文件说明详解
  15. sublime 设置自动更新_Win10关闭自动更新的三种方法
  16. MAC系统如何连接Windows共享文件?MAC系统连接Win共享文件的方法
  17. 考勤系统(打卡时间计算)
  18. ios 渐变透明背景_PPT设计的总是太单调,不如换个背景试试,超精彩!
  19. 被告知孩子学校偷钱后
  20. php微信退款aes,关于微信支付退款req_info字段解密问题

热门文章

  1. 正则表达式(参考百度词条)
  2. Endnote插入文献与文献管理
  3. java英雄联盟战斗力题目,Java 查询英雄联盟玩家战绩
  4. elasticdump工具安装及基操
  5. 1+2+3+...∞=-1/12?——杨子曰数学
  6. 每日学到 20 - 封装、访问修饰符
  7. Web开发基础——CSS
  8. 陈安之励志演讲经典句子
  9. CodeForces - 743B
  10. hdu 1983 Kaitou Kid - The Phantom Thief (2)【Bfs+暴力枚举】