一、HashMap使用

1、创建HashMap对象

HashMap<String,Integer> hashMap = new HashMap<>();
  • 线程不安全的哈希表
  • 键值对可以存储null,key不可以重复,value可以重复,重复时覆盖oldVlue
  • 取出的数据没有顺序

2、HashMap类常用方法

(1)put(K key, V value)

put(K key, V value) 将键(key)/值(value)映射存放到 Map集合中

map.put("Tom", 100);//向HashMap中添加元素

利用put()方法去添加元素时,元素的key不能重复,如果重复,则一定覆盖原先的value值

(2)get(Object key)

get(Object key) 返回 指定键所映射的值,没有该key对应的值则返回 null,

即获取key对应的value。

map.put("Tom", 100);
		map.put("Tom", 0);
		int score = map.get("Tom");// 获取key对应的value
		System.out.println(score);// key不允许重复,若重复,则覆盖已有key的value

(3)size()

size() 返回Map集合中数据数量,准确说是返回key-value的组数。

map.put("Tom", 100);
		map.put("Jim", 90);
		map.put("Sam", 91);
		System.out.println(map.size());

(4)isEmpty ()

isEmpty () 判断Map集合中是否有数据,如果没有则返回true,否则返回false

map.put("Tom", 100);
		map.put("Jim", 90);
		map.put("Sam", 91);
		System.out.println(map.isEmpty());

(5)remove(Object key)

remove(Object key) 删除Map集合中键为key的数据并返回其所对应value值。

map.put("Tom", 100);
		map.put("Jim", 90);
		map.put("Sam", 91);
		int score = map.remove("Tom");
		System.out.println(score);

(6)values()

values() 返回Map集合中所有value组成的以Collection数据类型格式数据。

map.put("Tom", 100);
		map.put("Jim", 90);
		map.put("Sam", 91);
		Collection<Integer> con = map.values();
		for (Integer score : con) {
			System.out.println(score);
		}

一般用于遍历HashMap集合中value值:

(7)遍历HashMap集合获取value值

a. ForEach
for (String v : map.values()) {
			System.out.println("value= " + v);
		}
b. Iterator迭代器
Iterator<String> iterator1 = map.values().iterator();
		while (iterator1.hasNext()) {
			String value = (String) iterator1.next();
    		System.out.println("value:" + value);
		}

二、HashMap底层结构

1. HashMap概述

  • HashMap是基于 哈希表的Map接口的非同步实现
  • Hashtable跟HashMap很像,唯一的区别是Hashtable中的方法是线程安全的。
  • HashMap 数据结构为 数组+链表,
  • 其中:链表的节点存储的是一个 Entry 对象,每个Entry 对象存储四个属性(hash,key,value,next)

hashmap快速创建 java 创建hashmap对象_红黑树

2. HashMap的重哈希(rehash)

当HashMap中的元素越来越多的时候,hash冲突的几率也就越来越高,因为数组的长度是固定的。所以为了提高查询的效率,就要对HashMap的数组进行扩容,而在HashMap数组扩容之后,最消耗性能的点就出现了:原数组中的数据必须重新计算其在新数组中的位置,并放进去,这就是rehash

当HashMap中的元素个数超过数组大小loadFactor时,就会进行数组扩容,loadFactor的默认值为0.75,这是一个折中的取值。也就是说,默认情况下,数组大小为16,那么当HashMap中元素个数超过160.75=12(这个值就是代码中的threshold值,也叫做临界值)的时候,就把数组的大小扩展为 2*16=32,即扩大一倍,然后重新计算每个元素在数组中的位置,而这是一个非常消耗性能的操作,所以如果我们已经预知HashMap中元素的个数,那么预设元素的个数能够有效的提高HashMap的性能

3. HashMap的扩容机制

HashMap 使用 “懒扩容”,只会在 PUT 的时候才进行判断,然后进行扩容。

  1. 将数组长度扩容为原来的2 倍
  2. 将原来数组中的元素进行重新放到新数组中

三、HashMap常见面试题

(1)JDK1.7与JDK1.8HashMap的区别和联系

  1. 最重要的一点是底层结构不一样,1.7是 数组+链表,1.8则是 数组+链表+红黑树结构;
  2. jdk1.7中当哈希表为空时,会先调用inflateTable()初始化一个数组;而1.8则是直接 调用resize()扩容;
  3. 插入键值对的put方法不的区别,1.8中会将节点插入到链表尾部,而1.7中是采用头插
  4. jdk1.7中的hash函数对哈希值的计算直接使用key的hashCode值,而1.8中则是采用key的hashCode异或上key的hashCode进行无符号右移16位的结果,避免了只靠低位数据来计算哈希时导致的冲突,计算结果由高低位结合决定,使元素分布更均匀;
  5. 扩容时1.8会保持原链表的顺序,而1.7会颠倒链表的顺序;而且1.8是在元素插入后检测是否需要扩容,1.7则是在元素插入前
  6. 扩容策略:1.7中是只要 不小于阈值就直接扩容2倍;而1.8的扩容策略会更优化,当 数组容量未达到64时,以2倍进行扩容,超过64之后若桶中元素个数不小于7就将链表转换为红黑树,但如果红黑树中的元素个数小于6就会还原为链表,当红黑树中元素不小于32的时候才会再次扩容。

(2)用过HashMap没?说说HashMap的结构(底层数据结构 + put方法描述)

  • HashMap是基于 哈希表的Map接口的非同步实现
  • Hashtable跟HashMap很像,唯一的区别是Hashtable中的方法是线程安全的
  • HashMap 数据结构为 数组+链表
  • 其中:链表的节点存储的是一个 Entry 对象,每个Entry 对象存储四个属性(hash,key,value,next)

a. put () 方法流程图

hashmap快速创建 java 创建hashmap对象_红黑树_02

b. put 源码分析

/**
 * 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);
}
/**
 * Computes key.hashCode() and spreads (XORs) higher bits of hash
 * to lower.  Because the table uses power-of-two masking, sets of
 * hashes that vary only in bits above the current mask will
 * always collide. (Among known examples are sets of Float keys
 * holding consecutive whole numbers in small tables.)  So we
 * apply a transform that spreads the impact of higher bits
 * downward. There is a tradeoff between speed, utility, and
 * quality of bit-spreading. Because many common sets of hashes
 * are already reasonably distributed (so don't benefit from
 * spreading), and because we use trees to handle large sets of
 * collisions in bins, we just XOR some shifted bits in the
 * cheapest possible way to reduce systematic lossage, as well as
 * to incorporate impact of the highest bits that would otherwise
 * never be used in index calculations because of table bounds.
 */
static final int hash(Object key) {
	int h;
    //通过hashCode()的高16位异或低16位实现
	return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
/**
 * 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;
	//底层存储数据的数组tab为空,进行第一次扩容,同时初始化tab
	if ((tab = table) == null || (n = tab.length) == 0)
		n = (tab = resize()).length;
	//计算要存储数据的下标index,如果当前位置为null,直接插入
	if ((p = tab[i = (n - 1) & hash]) == null)
		tab[i] = newNode(hash, key, value, null);
	else {
		Node<K,V> e; K k;
		//tab[i]的首个元素就是key,直接覆盖
		if (p.hash == hash &&
			((k = p.key) == key || (key != null && key.equals(k))))
			e = p;
		//tab[i]为TreeNode,进行红黑树的插入
		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);
					//链表长度大于8,转换为红黑树进行处理
					if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
						treeifyBin(tab, hash);
					break;
				}
				//找到已经存在的key,直接覆盖
				if (e.hash == hash &&
					((k = e.key) == key || (key != null && key.equals(k))))
					break;
				p = e;
			}
		}
		if (e != null) { // existing mapping for key
			V oldValue = e.value;
			if (!onlyIfAbsent || oldValue == null)
				e.value = value;
			afterNodeAccess(e);
			return oldValue;
		}
	}
	++modCount;
	//数据插入完成,size超过了扩容的阀值(容量*负载因子),进行扩容
	if (++size > threshold)
		resize();
	afterNodeInsertion(evict);
	return null;
}

总结

HashMap在put方法中,它使用 hashCode() 和equals()方法。当我们通过传递key-value对调用put方法的时候,HashMap使用Key hashCode()和哈希算法来找出存储key-value对的索引。如果索引处为空,则直接插入到对应的数组中,否则,判断是否是红黑树, 若是,则红黑树插入,否则遍历链表,若长度超过8,则将链表转为红黑树,转成功之后 再插入。

(3) 说说HashMap的扩容过程

HashMap 使用 “懒扩容”,只会在 PUT 的时候才进行判断,然后进行扩容。

  1. 将数组长度扩容为原来的2 倍
  2. 将原来数组中的元素进行重新放到新数组中