public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {}
public class Application {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("one", 101);
map.put(null, 0);
map.put("zero", null);
System.out.println(map.get("one"));
System.out.println(map.get(null));
System.out.println(map.get("ten"));
}
}
public class Application {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new HashMap<>();
System.out.println(map.put("one", 1));
System.out.println(map.put("one", 101));
}
}
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
/**
* 默认初始容量 - 必须是2的幂
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量。如果具有参数的任一构造函数隐式指定较高值,则使用最大容量。
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 在构造函数中未指定时使用的加载因子。
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* 链表-树 转换阈值
*/
static final int TREEIFY_THRESHOLD = 8;
/**
* 在调整大小期间 树-链表 转换阈值
*/
static final int UNTREEIFY_THRESHOLD = 6;
/**
* 最小树容量
*/
static final int MIN_TREEIFY_CAPACITY = 64;
/**
* 基础的内部维护节点,单向链表
*/
static class Node<K,V> implements Map.Entry<K,V> {
final int hash;
final K key;
V value;
Node<K,V> next;
// 全参构造、getter/setter、toString、hashCode、equals 略
}
/**
* 内部维护的二元数组,其大小始终为 2 的幂数
*/
transient Node<K,V>[] table;
/**
* 用作缓存的entrySet
*/
transient Set<Map.Entry<K,V>> entrySet;
/**
* key-value映射的数量
*/
transient int size;
/**
* 此HashMap经过结构修改的次数结构修改是指更改HashMap中映射数或以其他方式修改其内部结构(例如,重新散列)的修改。
*/
transient int modCount;
/**
* 下一个要调整大小的值(capacity * load factor)。
*/
int threshold;
/**
* 加载因子
*
* @serial
*/
final float loadFactor;
/**
* 使用指定的初始容量和加载因子构造一个空的HashMap。
*
* @param initialCapacity 初始容量
* @param loadFactor 加载因子
* @throws IllegalArgumentException 如果初始容量为负或加载因子为非正数
*/
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);
}
/**
* 使用指定的初始容量和默认加载因子(0.75)构造一个空的HashMap。
*
* @param initialCapacity 初始容量
* @throws IllegalArgumentException 初始容量为负
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 使用默认初始容量(16)和默认加载因子(0.75)构造一个空的HashMap。
*/
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
}
/**
* 调用putVal方法实现添加操作
*/
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;
// 如果在内部维护的tab[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))))
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))))
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;
// 如果容量大于下一个要调整大小的值,扩容至原大小的二倍并且重新散列
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
/**
* 当链表长度过长时将节点转变为红黑树以提高效率
* @param <K>
* @param <V>
*/
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
TreeNode<K, V> parent;
TreeNode<K, V> left;
TreeNode<K, V> right;
TreeNode<K, V> prev;
boolean red;
}
}
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
public class Application {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new LinkedHashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("one", 101);
map.put(null, 0);
map.put("zero", null);
System.out.println(map);
}
}
public class Hashtable<K,V>
extends Dictionary<K,V>
implements Map<K,V>, Cloneable, java.io.Serializable
public class Application {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new Hashtable<String, Integer>();
map.put("壹", 1);
map.put("贰", 2);
map.put("叁", 3);
map.put(null, 0); // key的内容为null
System.out.println(map);
}
}
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:464)
at com.alpha.demo.TestDemo.main(TestDemo.java:10)
public synchronized V put(K key, V value) {
if (value == null) {
throw new NullPointerException();
}
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
public class Application {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new TreeMap<>();
map.put("C", 3);
map.put("B", 2);
map.put("A", 1);
System.out.println(map);
}
}
static class Node<K,V> implements Map.Entry<K,V>
public interface Map<K, V> {
interface Entry<K, V> {}
}
public class Application {
public static void main(String[] args) throws Exception {
Map.Entry<String, Integer> entry = Map.entry("one", 1);
System.out.println("获取key:" + entry.getKey());
System.out.println("获取value:" + entry.getValue());
System.out.println(entry.getClass().getName());
}
}
public static interface Map.Entry<K,V>
public class Application {
public static void main(String[] args) throws Exception {
Map<String, Integer> map = new Hashtable<String, Integer>();
map.put("壹", 1);
map.put("贰", 2);
map.put("叁", 3);
// 将Map集合变为Set集合,目的是为了使用 iterator()方法
Set<Map.Entry<String, Integer>> set = map.entrySet();
Iterator<Map.Entry<String, Integer>> iter = set.iterator();
while (iter.hasNext()) {
Map.Entry<String, Integer> me = iter.next();
System.out.println(me.getKey() + " = " + me.getValue());
}
}
}