前言
以下内容基于jdk1.7.0_79源碼;
什麼是HashMap
基于哈希表的一個Map接口實作,存儲的對象是一個鍵值對對象(Entry<K,V>);
HashMap補充說明
基于數組和連結清單實作,内部維護着一個數組table,該數組儲存着每個連結清單的表頭結點;查找時,先通過hash函數計算key的hash值,再根據key的hash值計算數組索引(取餘法),然後根據索引找到連結清單表頭結點,然後周遊查找該連結清單;
HashMap資料結構
畫了個示意圖,如下,左邊的數組索引是根據key的hash值計算得到,不同hash值有可能産生一樣的索引,即哈希沖突,此時采用鍊位址法處理哈希沖突,即将所有索引一緻的節點構成一個單連結清單;

HashMap繼承的類與實作的接口
Map接口,方法的含義很簡單,基本上看個方法名就知道了,後面會在HashMap源碼分析裡詳細說明
AbstractMap抽象類中定義的方法
HashMap源碼分析,大部分都加了注釋
package java.util;
import java.io.*;
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
/**
* 預設初始容量,預設為2的4次方 = 16,2的n次方是為了加快hash計算速度,;;減少hash沖突,,,h & (length-1),,1111111
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* 最大容量,預設為2的30次方,
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/**
* 預設負載因子,預設為0.75
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
*當數組表還沒擴容的時候,一個共享的空表對象
*/
static final Entry<?,?>[] EMPTY_TABLE = {};
/**
* 數組表,大小可以改變,且大小必須為2的幂
*/
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
/**
* 目前Map中key-value映射的個數
*/
transient int size;
/**
* 下次擴容門檻值,當size > capacity * load factor時,開始擴容
*/
int threshold;
/**
* 負載因子
*/
final float loadFactor;
/**
* Hash表結構性修改次數,用于實作疊代器快速失敗行為
*/
transient int modCount;
/**
* 容量門檻值,預設大小為Integer.MAX_VALUE
*/
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
/**
* 靜态内部類Holder,存放一些隻能在虛拟機啟動後才能初始化的值
*/
private static class Holder {
/**
* 容量門檻值,初始化hashSeed的時候會用到該值
*/
static final int ALTERNATIVE_HASHING_THRESHOLD;
static {
//擷取系統變量jdk.map.althashing.threshold
String altThreshold = java.security.AccessController.doPrivileged(
new sun.security.action.GetPropertyAction(
"jdk.map.althashing.threshold"));
int threshold;
try {
threshold = (null != altThreshold)
? Integer.parseInt(altThreshold)
: ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;
// jdk.map.althashing.threshold系統變量預設為-1,如果為-1,則将門檻值設為Integer.MAX_VALUE
if (threshold == -1) {
threshold = Integer.MAX_VALUE;
}
//門檻值需要為正數
if (threshold < 0) {
throw new IllegalArgumentException("value must be positive integer.");
}
} catch(IllegalArgumentException failed) {
throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
}
ALTERNATIVE_HASHING_THRESHOLD = threshold;
}
}
/**
* 計算hash值的時候需要用到
*/
transient int hashSeed = 0;
/**
* 生成一個空的HashMap,并指定其容量大小和負載因子
*
*/
public HashMap(int initialCapacity, float loadFactor) {
//保證初始容量大于等于0
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
//保證初始容量不大于最大容量MAXIMUM_CAPACITY
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
//loadFactor小于0或為無效數字
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
//負載因子
this.loadFactor = loadFactor;
//下次擴容大小
threshold = initialCapacity;
init();
}
/**
* 生成一個空的HashMap,并指定其容量大小,負載因子使用預設的0.75
*
*/
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
/**
* 生成一個空的HashMap,容量大小使用預設值16,負載因子使用預設值0.75
*/
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
/**
* 根據指定的map生成一個新的HashMap,負載因子使用預設值,初始容量大小為Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,DEFAULT_INITIAL_CAPACITY)
*/
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
inflateTable(threshold);
putAllForCreate(m);
}
//傳回>=number的最小2的n次方值,如number=5,則傳回8
private static int roundUpToPowerOf2(int number) {
// assert number >= 0 : "number must be non-negative";
return number >= MAXIMUM_CAPACITY
? MAXIMUM_CAPACITY
: (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}
/**
* 對table擴容
*/
private void inflateTable(int toSize) {
// Find a power of 2 >= toSize
//找一個值(2的n次方,且>=toSize)
int capacity = roundUpToPowerOf2(toSize);
//下次擴容門檻值
threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
table = new Entry[capacity];
initHashSeedAsNeeded(capacity);
}
// internal utilities
void init() {
}
/**
* 初始化hashSeed
*/
final boolean initHashSeedAsNeeded(int capacity) {
boolean currentAltHashing = hashSeed != 0;
boolean useAltHashing = sun.misc.VM.isBooted() &&
(capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
boolean switching = currentAltHashing ^ useAltHashing;
if (switching) {
hashSeed = useAltHashing
? sun.misc.Hashing.randomHashSeed(this)
: 0;
}
return switching;
}
/**
* 生成hash值
*/
final int hash(Object k) {
int h = hashSeed;
//如果key是字元串,調用un.misc.Hashing.stringHash32生成hash值
//Oracle表示能生成更好的hash分布,不過這在jdk8中已删除
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash32((String) k);
}
//一次散列,調用k的hashCode方法,與hashSeed做異或操作
h ^= k.hashCode();
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
//二次散列,
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
/**
* 傳回hash值的索引,采用除模取餘法,h & (length-1)操作 等價于 hash % length操作, 但&操作性能更優
*/
static int indexFor(int h, int length) {
// assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
return h & (length-1);
}
/**
* 傳回key-value映射個數
*/
public int size() {
return size;
}
/**
* 判斷map是否為空
*/
public boolean isEmpty() {
return size == 0;
}
/**
* 傳回指定key對應的value
*/
public V get(Object key) {
//key為null情況
if (key == null)
return getForNullKey();
//根據key查找節點
Entry<K,V> entry = getEntry(key);
//傳回key對應的值
return null == entry ? null : entry.getValue();
}
/**
* 查找key為null的value,注意如果key為null,則其hash值為0,預設是放在table[0]裡的
*/
private V getForNullKey() {
if (size == 0) {
return null;
}
//在table[0]的連結清單上查找key為null的鍵值對,因為null預設是存在table[0]的桶裡
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
if (e.key == null)
return e.value;
}
return null;
}
/**
*判斷是否包含指定的key
*/
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
/**
* 根據key查找鍵值對,找不到傳回null
*/
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
//如果key為null,hash值為0,否則調用hash方法,對key生成hash值
int hash = (key == null) ? 0 : hash(key);
//調用indexFor方法生成hash值的索引,周遊該索引下的連結清單,查找key“相等”的鍵值對
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
return null;
}
/**
* 向map存入一個鍵值對,如果key已存在,則覆寫
*/
public V put(K key, V value) {
//數組為空,對數組擴容
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
//對key為null的鍵值對調用putForNullKey處理
if (key == null)
return putForNullKey(value);
//生成hash值
int hash = hash(key);
//生成hash值索引
int i = indexFor(hash, table.length);
//查找是否有key“相等”的鍵值對,有的話覆寫
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//操作次數加一,用于疊代器快速失敗行為
modCount++;
//在指定hash值索引處的連結清單上增加該鍵值對
addEntry(hash, key, value, i);
return null;
}
/**
* 存放key為null的鍵值對,存放在索引為0的連結清單上,已存在的話,替換
*/
private V putForNullKey(V value) {
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
//已存在key為null,則替換
if (e.key == null) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
//操作次數加一,用于疊代器快速失敗行為
modCount++;
//在指定hash值索引處的連結清單上增加該鍵值對
addEntry(0, null, value, 0);
return null;
}
/**
* 添加鍵值對
*/
private void putForCreate(K key, V value) {
//生成hash值
int hash = null == key ? 0 : hash(key);
//生成hash值索引,
int i = indexFor(hash, table.length);
/**
* key“相等”,則替換
*/
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
e.value = value;
return;
}
}
//在指定索引處的連結清單上建立該鍵值對
createEntry(hash, key, value, i);
}
//将制定map的鍵值對添加到map中
private void putAllForCreate(Map<? extends K, ? extends V> m) {
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
putForCreate(e.getKey(), e.getValue());
}
/**
* 對數組擴容
*/
void resize(int newCapacity) {
Entry[] oldTable = table;
int oldCapacity = oldTable.length;
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
//建立一個指定大小的數組
Entry[] newTable = new Entry[newCapacity];
transfer(newTable, initHashSeedAsNeeded(newCapacity));
//table索引替換成新數組
table = newTable;
//重新計算門檻值
threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
}
/**
* 拷貝舊的鍵值對到新的哈希表中
*/
void transfer(Entry[] newTable, boolean rehash) {
int newCapacity = newTable.length;
//周遊舊的數組
for (Entry<K,V> e : table) {
while(null != e) {
Entry<K,V> next = e.next;
if (rehash) {
e.hash = null == e.key ? 0 : hash(e.key);
}
//根據新的數組長度,重新計算索引,
int i = indexFor(e.hash, newCapacity);
//插入到連結清單表頭
e.next = newTable[i];
//将e放到索引為i處
newTable[i] = e;
//将e設定成下個節點
e = next;
}
}
}
/**
* 将制定map的鍵值對put到本map,key“相等”的直接覆寫
*/
public void putAll(Map<? extends K, ? extends V> m) {
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
//空map,擴容
if (table == EMPTY_TABLE) {
inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
}
/*
* 判斷是否需要擴容
*/
if (numKeysToBeAdded > threshold) {
int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
if (targetCapacity > MAXIMUM_CAPACITY)
targetCapacity = MAXIMUM_CAPACITY;
int newCapacity = table.length;
while (newCapacity < targetCapacity)
newCapacity <<= 1;
if (newCapacity > table.length)
resize(newCapacity);
}
//依次周遊鍵值對,并put
for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
put(e.getKey(), e.getValue());
}
/**
* 移除指定key的鍵值對
*/
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
/**
* 移除指定key的鍵值對
*/
final Entry<K,V> removeEntryForKey(Object key) {
if (size == 0) {
return null;
}
//計算hash值及索引
int hash = (key == null) ? 0 : hash(key);
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
//頭節點為table[i]的單連結清單上執行删除節點操作
while (e != null) {
Entry<K,V> next = e.next;
Object k;
//找到要删除的節點
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
/**
* 删除指定鍵值對對象(Entry對象)
*/
final Entry<K,V> removeMapping(Object o) {
if (size == 0 || !(o instanceof Map.Entry))
return null;
Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
Object key = entry.getKey();
int hash = (key == null) ? 0 : hash(key);
//得到數組索引
int i = indexFor(hash, table.length);
Entry<K,V> prev = table[i];
Entry<K,V> e = prev;
//開始周遊該單連結清單
while (e != null) {
Entry<K,V> next = e.next;
//找到節點
if (e.hash == hash && e.equals(entry)) {
modCount++;
size--;
if (prev == e)
table[i] = next;
else
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
/**
* 清空map,将table數組所有元素設為null
*/
public void clear() {
modCount++;
Arrays.fill(table, null);
size = 0;
}
/**
* 判斷是否含有指定value的鍵值對
*/
public boolean containsValue(Object value) {
if (value == null)
return containsNullValue();
Entry[] tab = table;
//周遊table數組
for (int i = 0; i < tab.length ; i++)
//周遊每條單連結清單
for (Entry e = tab[i] ; e != null ; e = e.next)
if (value.equals(e.value))
return true;
return false;
}
/**
* 判斷是否含有value為null的鍵值對
*/
private boolean containsNullValue() {
Entry[] tab = table;
for (int i = 0; i < tab.length ; i++)
for (Entry e = tab[i] ; e != null ; e = e.next)
if (e.value == null)
return true;
return false;
}
/**
* 淺拷貝,鍵值對不複制
*/
public Object clone() {
HashMap<K,V> result = null;
try {
result = (HashMap<K,V>)super.clone();
} catch (CloneNotSupportedException e) {
// assert false;
}
if (result.table != EMPTY_TABLE) {
result.inflateTable(Math.min(
(int) Math.min(
size * Math.min(1 / loadFactor, 4.0f),
// we have limits...
HashMap.MAXIMUM_CAPACITY),
table.length));
}
result.entrySet = null;
result.modCount = 0;
result.size = 0;
result.init();
result.putAllForCreate(this);
return result;
}
//内部類,節點對象,每個節點包含下個節點的引用
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
int hash;
/**
* 建立節點
*/
Entry(int h, K k, V v, Entry<K,V> n) {
value = v;
next = n;
key = k;
hash = h;
}
//擷取節點的key
public final K getKey() {
return key;
}
//擷取節點的value
public final V getValue() {
return value;
}
//設定新value,并傳回舊的value
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//判斷key和value是否相同,兩個都“相等”,傳回true
public final boolean equals(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry e = (Map.Entry)o;
Object k1 = getKey();
Object k2 = e.getKey();
if (k1 == k2 || (k1 != null && k1.equals(k2))) {
Object v1 = getValue();
Object v2 = e.getValue();
if (v1 == v2 || (v1 != null && v1.equals(v2)))
return true;
}
return false;
}
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
}
public final String toString() {
return getKey() + "=" + getValue();
}
/**
* This method is invoked whenever the value in an entry is
* overwritten by an invocation of put(k,v) for a key k that's already
* in the HashMap.
*/
void recordAccess(HashMap<K,V> m) {
}
/**
* This method is invoked whenever the entry is
* removed from the table.
*/
void recordRemoval(HashMap<K,V> m) {
}
}
/**
* 添加新節點,如有必要,執行擴容操作
*/
void addEntry(int hash, K key, V value, int bucketIndex) {
if ((size >= threshold) && (null != table[bucketIndex])) {
resize(2 * table.length);
hash = (null != key) ? hash(key) : 0;
bucketIndex = indexFor(hash, table.length);
}
createEntry(hash, key, value, bucketIndex);
}
/**
* 插入單連結清單表頭
*/
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<>(hash, key, value, e);
size++;
}
//hashmap疊代器
private abstract class HashIterator<E> implements Iterator<E> {
Entry<K,V> next; // 下個鍵值對索引
int expectedModCount; // 用于判斷快速失敗行為
int index; // current slot
Entry<K,V> current; // current entry
HashIterator() {
expectedModCount = modCount;
if (size > 0) { // advance to first entry
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
}
public final boolean hasNext() {
return next != null;
}
final Entry<K,V> nextEntry() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Entry<K,V> e = next;
if (e == null)
throw new NoSuchElementException();
if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
current = e;
return e;
}
public void remove() {
if (current == null)
throw new IllegalStateException();
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
Object k = current.key;
current = null;
HashMap.this.removeEntryForKey(k);
expectedModCount = modCount;
}
}
//ValueIterator疊代器
private final class ValueIterator extends HashIterator<V> {
public V next() {
return nextEntry().value;
}
}
//KeyIterator疊代器
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
////KeyIterator疊代器
private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}
// 傳回疊代器方法
Iterator<K> newKeyIterator() {
return new KeyIterator();
}
Iterator<V> newValueIterator() {
return new ValueIterator();
}
Iterator<Map.Entry<K,V>> newEntryIterator() {
return new EntryIterator();
}
// Views
private transient Set<Map.Entry<K,V>> entrySet = null;
/**
* 傳回一個set集合,包含key
*/
public Set<K> keySet() {
Set<K> ks = keySet;
return (ks != null ? ks : (keySet = new KeySet()));
}
private final class KeySet extends AbstractSet<K> {
public Iterator<K> iterator() {
return newKeyIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsKey(o);
}
public boolean remove(Object o) {
return HashMap.this.removeEntryForKey(o) != null;
}
public void clear() {
HashMap.this.clear();
}
}
/**
* 傳回一個value集合,包含value
*/
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}
private final class Values extends AbstractCollection<V> {
public Iterator<V> iterator() {
return newValueIterator();
}
public int size() {
return size;
}
public boolean contains(Object o) {
return containsValue(o);
}
public void clear() {
HashMap.this.clear();
}
}
/**
* 傳回一個鍵值對集合
*/
public Set<Map.Entry<K,V>> entrySet() {
return entrySet0();
}
private Set<Map.Entry<K,V>> entrySet0() {
Set<Map.Entry<K,V>> es = entrySet;
return es != null ? es : (entrySet = new EntrySet());
}
private final class EntrySet extends AbstractSet<Map.Entry<K,V>> {
public Iterator<Map.Entry<K,V>> iterator() {
return newEntryIterator();
}
public boolean contains(Object o) {
if (!(o instanceof Map.Entry))
return false;
Map.Entry<K,V> e = (Map.Entry<K,V>) o;
Entry<K,V> candidate = getEntry(e.getKey());
return candidate != null && candidate.equals(e);
}
public boolean remove(Object o) {
return removeMapping(o) != null;
}
public int size() {
return size;
}
public void clear() {
HashMap.this.clear();
}
}
/**
* map序列化,可實作深拷貝
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Write out the threshold, loadfactor, and any hidden stuff
s.defaultWriteObject();
// Write out number of buckets
if (table==EMPTY_TABLE) {
s.writeInt(roundUpToPowerOf2(threshold));
} else {
s.writeInt(table.length);
}
// Write out size (number of Mappings)
s.writeInt(size);
// Write out keys and values (alternating)
if (size > 0) {
for(Map.Entry<K,V> e : entrySet0()) {
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
private static final long serialVersionUID = 362498820763181265L;
/**
* 反序列化,讀取位元組碼轉為對象
*/
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
// Read in the threshold (ignored), loadfactor, and any hidden stuff
s.defaultReadObject();
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
// set other fields that need values
table = (Entry<K,V>[]) EMPTY_TABLE;
// Read in number of buckets
s.readInt(); // ignored.
// Read number of mappings
int mappings = s.readInt();
if (mappings < 0)
throw new InvalidObjectException("Illegal mappings count: " +
mappings);
// capacity chosen by number of mappings and desired load (if >= 0.25)
int capacity = (int) Math.min(
mappings * Math.min(1 / loadFactor, 4.0f),
// we have limits...
HashMap.MAXIMUM_CAPACITY);
// allocate the bucket array;
if (mappings > 0) {
inflateTable(capacity);
} else {
threshold = capacity;
}
init(); // Give subclass a chance to do its thing.
// Read the keys and values, and put the mappings in the HashMap
for (int i = 0; i < mappings; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
// These methods are used when serializing HashSets
int capacity() { return table.length; }
float loadFactor() { return loadFactor; }
}
}
簡單使用示例
package com.pichen.collection;
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
//put方法
map.put("A", 5);
map.put("B", 6);
map.put("C", 7);
map.put("D", 8);
//重寫了toString方法
System.out.println(map);
//size方法
System.out.println(map.size());
System.out.println(map.containsKey("A"));
System.out.println(map.containsValue(6));
System.out.println(map.get("B"));
//remove
map.remove("C");
System.out.println(map);
//key集合
for(String str:map.keySet()){
System.out.print(str + " ");
}
System.out.println();
//value集合
for(Integer obj:map.values()){
System.out.print(obj + " ");
}
System.out.println();
//key-value集合
for(Map.Entry<String, Integer> entry:map.entrySet()){
System.out.print(entry.getKey() + ": " + entry.getValue() + ", ");
}
}
}
@Author 風一樣的碼農
@HomePageUrl http://www.cnblogs.com/chenpi/
@Copyright 轉載請注明出處,謝謝~