hashMap的基本结构是:数组和链表(java的基本存储结构)
以下是hashMap的几个重要函数源码
put源码:
public V put(K key,V value){
if(table == EMPTY_TABLE){
inflateTable(threshold);
}
if(key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash,table.length);
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++;
addEntry(hash,key,value,i);
return null;
}
其中根据每个key进行hash,hash的源码如下:
final int hash(Object k){
int h = hashSeed;
if(0!=h&& k instanceof String){
return sun.misc.Hashing.stringHash32((String) k);
}
h^=k.hashCode();
h^=(h>>>20)^(h>>>12);
return h^(h>>>7)^(h>>>4);
}
其中indexFor函数的源码如下:
static int indexFor(int h,int length){
return h&(length-1);
}
hash的作用就是把每个put进来的值,通过key的移位与运算,来实现分布均匀,最好的情况就是hashMap数组中的每一个位置都有一个值。每次put进去的时候,hashMap的size++,当size大于容量的时候,通过resize函数来使当前的hashMap大小扩容为原来的两倍,内部实现就是再创建一个新的数组,然后通过tranfer来把元素拷贝过去。
tranfer函数的源码如下:
void tranfer(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];
newTable[i]=e;
e=next;
}
}
}
分析:因为table的length变了,所以indexFor返回的值有可能会发生变化,所以说HashMap的元素顺序是乱序的。Map中treeMap和LinkedHashMap是有序,以后会分析一下这两个中的有序是如何实现的。
以上中的Entry的结构是:
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;
}
}