这篇文章给大家介绍深入浅析Java中HashMap与HashTable容器的区别,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

1、HashMap
HashMap继承抽象类AbstractMap,实现接口Map、Cloneable, Serializable接口。HashMap是一种以键值对存储数据的容器,
由数组+链表组成,其中key和value都可以为空,key的值唯一。HashMap是非线程安全的, 对于键值对
HashMap内部会将其封装成一个对应的Entry对象。HashMap的存储空间大小是可以动态改变的:
存储过程
每个对象都有一个对应的HashCode值,根据HashCode值,调用hash函数,计算出一个hash值,根据该hash值调用indexFor函数,计算出在table中的存储位置,如果该位置已经有值,则存储在该位置对应的桶中。
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 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;
}
public final int hash(Object k) {
int h = hashSeed;
if (0 != h && k instanceof String) {
return sun.misc.Hashing.stringHash42((String) k);
}
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);
}
public final int hashCode() {
return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue())
}
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);
}