Java HashMapソース注釈
73047 ワード
Java HashMapのソースコードの注釈は、後で確認するのに便利です.
package java.util;
import java.io.*;
public class HashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable
{
// , 2 n ,
static final int DEFAULT_INITIAL_CAPACITY = 16;
//
static final int MAXIMUM_CAPACITY = 1 << 30;
// ,
static final float DEFAULT_LOAD_FACTOR = 0.75f;
// , , 2 n
transient Entry[] table;
// map key-value , size
transient int size;
//
int threshold;
//
final float loadFactor;
// ,HashMap
transient volatile int modCount;
// HashMap。
public HashMap(int initialCapacity, float loadFactor) {
// 0,
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
// ,
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
// loadFactor 0, loadFactor NaN,
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
// 2 k capacity initialCapacity
int capacity = 1;
while (capacity < initialCapacity)
capacity <<= 1;
//
this.loadFactor = loadFactor;
// capacity * loadFactor, HashMap size ,HashMap 。
threshold = (int)(capacity * loadFactor);
// capacity
table = new Entry[capacity];
//
init();
}
// (0.75) HashMap。
public HashMap(int initialCapacity) {
this(initialCapacity, DEFAULT_LOAD_FACTOR);
}
// (16) (0.75) HashMap。
public HashMap() {
this.loadFactor = DEFAULT_LOAD_FACTOR;
threshold = (int)(DEFAULT_INITIAL_CAPACITY * DEFAULT_LOAD_FACTOR);
table = new Entry[DEFAULT_INITIAL_CAPACITY];
init();
}
// Map HashMap。
public HashMap(Map<? extends K, ? extends V> m) {
this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1,
DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
putAllForCreate(m);
}
//
// , ,
void init() {
}
// hash , hash ,
static int hash(int h) {
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
// hash
static int indexFor(int h, int length) {
/*****************
* length 2 n , h & (length-1) h % length。
* length, 2 1000...0, length-1 0111...1。
* length h, h。
* h = length, 0。
* length h, 0111...1 ,
* 0111...1 0,
* j length, h-j*length,
* h % length。
* h & 1 h % 2。
* length 2 n , 。
*/
return h & (length-1);
}
// map key-value , size
public int size() {
return size;
}
// HashMap , size 0,
public boolean isEmpty() {
return size == 0;
}
// ; , , null
public V get(Object key) {
// key null
if (key == null)
return getForNullKey();
// hashCode
int hash = hash(key.hashCode());
// hash , , next
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
// hash , key
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
// , , null
return null;
}
// key null ,
private V getForNullKey() {
// table[0]
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
// key null,
if (e.key == null)
return e.value;
}
// null
return null;
}
// , true
public boolean containsKey(Object key) {
return getEntry(key) != null;
}
// key value
final Entry<K,V> getEntry(Object key) {
// key null, hash 0, hash
int hash = (key == null) ? 0 : hash(key.hashCode());
// hash , , next
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e != null;
e = e.next) {
Object k;
// hash , key
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
return e;
}
// , , null
return null;
}
// 。 ,
public V put(K key, V value) {
// key null putForNullKey
if (key == null)
return putForNullKey(value);
// hash hashCode
int hash = hash(key.hashCode());
//
int i = indexFor(hash, table.length);
// hash , , next
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// hash key
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
// value
V oldValue = e.value;
// value
e.value = value;
e.recordAccess(this);
// value
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
// key null value
private V putForNullKey(V value) {
// table[0]
for (Entry<K,V> e = table[0]; e != null; e = e.next) {
// key null
if (e.key == null) {
// oldValue, value
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
// oldValue
return oldValue;
}
}
modCount++;
addEntry(0, null, value, 0);
return null;
}
//
private void putForCreate(K key, V value) {
// key null, hash 0, hash
int hash = (key == null) ? 0 : hash(key.hashCode());
//
int i = indexFor(hash, table.length);
//
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
// hash , key , ,
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
e.value = value;
return;
}
}
//
createEntry(hash, key, value, i);
}
// Map
private void putAllForCreate(Map<? extends K, ? extends V> m) {
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<? extends K, ? extends V> e = i.next();
putForCreate(e.getKey(), e.getValue());
}
}
// resize HashMap
void resize(int newCapacity) {
// oldTable
Entry[] oldTable = table;
//
int oldCapacity = oldTable.length;
// , ,
if (oldCapacity == MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return;
}
// table
Entry[] newTable = new Entry[newCapacity];
// table newTable
transfer(newTable);
// table newTable
table = newTable;
//
threshold = (int)(newCapacity * loadFactor);
}
// table
void transfer(Entry[] newTable) {
// table
Entry[] src = table;
//
int newCapacity = newTable.length;
// src
for (int j = 0; j < src.length; j++) {
// ( )
Entry<K,V> e = src[j];
// e
if (e != null) {
// null
src[j] = null;
//
do {
//
Entry<K,V> next = e.next;
//
int i = indexFor(e.hash, newCapacity);
// e.next newTable[i] ( )
e.next = newTable[i];
// e newTable[i]
newTable[i] = e;
// e
e = next;
} while (e != null);
}
}
}
// ,
public void putAll(Map<? extends K, ? extends V> m) {
//
int numKeysToBeAdded = m.size();
if (numKeysToBeAdded == 0)
return;
//
if (numKeysToBeAdded > threshold) {
// resize
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);
}
// key-value HashMap
for (Iterator<? extends Map.Entry<? extends K, ? extends V>> i = m.entrySet().iterator(); i.hasNext(); ) {
Map.Entry<? extends K, ? extends V> e = i.next();
put(e.getKey(), e.getValue());
}
}
// ( )
public V remove(Object key) {
Entry<K,V> e = removeEntryForKey(key);
return (e == null ? null : e.value);
}
// key , value
final Entry<K,V> removeEntryForKey(Object key) {
int hash = (key == null) ? 0 : hash(key.hashCode());
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;
Object k;
//
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k)))) {
modCount++;
// size 1
size--;
//
if (prev == e)
// table[i]
table[i] = next;
else
//
prev.next = next;
e.recordRemoval(this);
return e;
}
prev = e;
e = next;
}
return e;
}
// map
final Entry<K,V> removeMapping(Object o) {
// o Map.Entry , null
if (!(o instanceof Map.Entry))
return null;
// o Map.Entry
Map.Entry<K,V> entry = (Map.Entry<K,V>) o;
// key
Object key = entry.getKey();
// hash
int hash = (key == null) ? 0 : hash(key.hashCode());
//
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;
}
// 。 ,
public void clear() {
modCount++;
Entry[] tab = table;
// table , null
for (int i = 0; i < tab.length; i++)
tab[i] = null;
// size 0
size = 0;
}
// , true
public boolean containsValue(Object value) {
// value , containsNullValue
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)
// , true
if (value.equals(e.value))
return true;
// false
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;
}
// HashMap :
public Object clone() {
HashMap<K,V> result = null;
try {
result = (HashMap<K,V>)super.clone();
} catch (CloneNotSupportedException e) {
// assert false;
}
result.table = new Entry[table.length];
result.entrySet = null;
result.modCount = 0;
result.size = 0;
result.init();
result.putAllForCreate(this);
return result;
}
// class ,
static class Entry<K,V> implements Map.Entry<K,V> {
final K key;
V value;
Entry<K,V> next;
final 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
public final V setValue(V newValue) {
V oldValue = value;
value = newValue;
return oldValue;
}
//
public final boolean equals(Object o) {
// o Map.Entry ,
if (!(o instanceof Map.Entry))
return false;
// o Map.Entry
Map.Entry e = (Map.Entry)o;
// key value , true
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;
}
// false
return false;
}
// hashCode
public final int hashCode() {
return (key==null ? 0 : key.hashCode()) ^
(value==null ? 0 : value.hashCode());
}
// String
public final String toString() {
return getKey() + "=" + getValue();
}
// key map
void recordAccess(HashMap<K,V> m) {
}
// key
void recordRemoval(HashMap<K,V> m) {
}
}
// key value
void addEntry(int hash, K key, V value, int bucketIndex) {
// table
Entry<K,V> e = table[bucketIndex];
// ,
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
// size
if (size++ >= threshold)
//
resize(2 * table.length);
}
// ,
void createEntry(int hash, K key, V value, int bucketIndex) {
Entry<K,V> e = table[bucketIndex];
table[bucketIndex] = new Entry<K,V>(hash, key, value, e);
size++;
}
// class HashIterator
private abstract class HashIterator<E> implements Iterator<E> {
Entry<K,V> next; //
int expectedModCount; // HashMap
int index; //
Entry<K,V> current; //
//
HashIterator() {
// modCount, HashMap modCount , modCount ,
expectedModCount = modCount;
//
if (size > 0) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
}
//
public final boolean hasNext() {
return next != null;
}
//
final Entry<K,V> nextEntry() {
// modCount ,
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// next
Entry<K,V> e = next;
// next ,
if (e == null)
throw new NoSuchElementException();
// next.next , next ,
if ((next = e.next) == null) {
Entry[] t = table;
while (index < t.length && (next = t[index++]) == null)
;
}
// current
current = e;
// e
return e;
}
//
public void remove() {
// ,
if (current == null)
throw new IllegalStateException();
// modCount ,
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
// key
Object k = current.key;
// current null
current = null;
// key
HashMap.this.removeEntryForKey(k);
// expectedModCount
expectedModCount = modCount;
}
}
// class ValueIterator , next
private final class ValueIterator extends HashIterator<V> {
public V next() {
return nextEntry().value;
}
}
// class KeyIterator , next
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
// class EntryIterator , next
private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}
// iterator()
Iterator<K> newKeyIterator() {
return new KeyIterator();
}
Iterator<V> newValueIterator() {
return new ValueIterator();
}
Iterator<Map.Entry<K,V>> newEntryIterator() {
return new EntryIterator();
}
private transient Set<Map.Entry<K,V>> entrySet = null;
/**
* Set 。
* set , set ,
* 。 set ( remove ),
* 。 set ,
* Iterator.remove、Set.remove、removeAll、retainAll clear
* 。 add addAll 。
*/
public Set<K> keySet() {
Set<K> ks = keySet;
// keySet , KeySet
return (ks != null ? ks : (keySet = new KeySet()));
}
// KeySet
private final class KeySet extends AbstractSet<K> {
// iterator
public Iterator<K> iterator() {
return newKeyIterator();
}
// size
public int size() {
return size;
}
// contains
public boolean contains(Object o) {
return containsKey(o);
}
// remove
public boolean remove(Object o) {
return HashMap.this.removeEntryForKey(o) != null;
}
// clear
public void clear() {
HashMap.this.clear();
}
}
/**
* Collection 。
* collection , collection ,
* 。 collection ( remove ),
* 。 collection ,
* Iterator.remove、Collection.remove、removeAll、retainAll clear
* 。 add addAll 。
*/
public Collection<V> values() {
Collection<V> vs = values;
return (vs != null ? vs : (values = new Values()));
}
// 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();
}
}
/**
* Set 。
* set , set ,
* 。 set
* ( remove , setValue ),
* 。 set ,
* Iterator.remove、Set.remove、removeAll、retainAll clear
* 。 add addAll 。
*/
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());
}
// 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();
}
}
//
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
Iterator<Map.Entry<K,V>> i =
(size > 0) ? entrySet0().iterator() : null;
s.defaultWriteObject();
s.writeInt(table.length);
s.writeInt(size);
if (i != null) {
while (i.hasNext()) {
Map.Entry<K,V> e = i.next();
s.writeObject(e.getKey());
s.writeObject(e.getValue());
}
}
}
private static final long serialVersionUID = 362498820763181265L;
//
private void readObject(java.io.ObjectInputStream s)
throws IOException, ClassNotFoundException
{
s.defaultReadObject();
int numBuckets = s.readInt();
table = new Entry[numBuckets];
init();
int size = s.readInt();
for (int i=0; i<size; i++) {
K key = (K) s.readObject();
V value = (V) s.readObject();
putForCreate(key, value);
}
}
int capacity() { return table.length; }
float loadFactor() { return loadFactor; }
}