参考的文档
阅读JDK1.8 HashMap源码分析
阅读源码
jdk1.8 HashMap的数据结构
数组+链表+红黑树
HashMap使用hash()方法来决定元素在数组位置,因为hash算法会出现过个元素的的hash()返回的值是一样的,它用链表存放这些hash值相同的元素,jdk1.6是用数组和链表实现的,在1.8里面当链表的长度(阀值)超过8,就会转为红黑树。
一些方法的使用
package com.fang.javalearn.javalearn.collection.map;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import java.util.Map.Entry;
import java.util.concurrent.CopyOnWriteArrayList;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class HashMapTest {
public static void main(String[] args) {
testHashMap();
}
private static void testHashMap() {
Random ran = new Random();
HashMap<String, Integer> map = new HashMap<>();
map.put("one", ran.nextInt(100));
map.put("two", ran.nextInt(100));
map.put("three", ran.nextInt(100));
// one iterator
/*
* Iterator it = map.entrySet().iterator(); while (it.hasNext()) { Entry entry =
* (Entry) it.next(); log.info("key:" + entry.getKey() + ",value:" +
* entry.getValue()); }
*/
// two iterator 泛型
Iterator<Map.Entry<String, Integer>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
log.info("key:" + entry.getKey() + ",value:" + entry.getValue());
}
//
log.info("map size {}", map.size());
// contains key
log.info("map contains key " + "one:" + map.containsKey("two"));
log.info("map contains key" + "nine:" + map.containsKey("nine"));
// contains value
log.info("contain value 0:" + map.containsValue(new Integer(0)));
// remove
map.remove("one");
log.info("map contains key " + "one:" + map.containsKey("two"));
// clear()
map.clear();
while (iterator.hasNext()) {
Map.Entry<String, Integer> entry = iterator.next();
log.info("key:" + entry.getKey() + ",value:" + entry.getValue());
}
log.info("map size {}", map.size());
}
}