类的继承关系
HashMap中的对象可以被拷贝 克隆 序列到磁盘上,WeakhashMap都不行
重要方法
- WeakhashMap的put方法(key重复,新值覆盖旧值;头插新节点)
- hash算法不一样(WeakhashMap源码297行 )
/**
* Retrieve object hash code and applies a supplemental hash function to the
* result hash, which defends against poor quality hash functions. This is
* critical because HashMap uses power-of-two length hash tables, that
* otherwise encounter collisions for hashCodes that do not differ
* in lower bits.
*/
final int hash(Object k) {
int 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);
}
//HashMap337行
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
- put(447行)不能放键为NULL,系统会自动new一个 NULLKEY,HashMap的key和value都可以为null;
- WeakhashMap中的
put/get/remove/resize等方法均会使用expungeStaleEntries()方法,用来遍历ReferenceQueue找到里面的key所对应的结点清除掉
使用场景
WeakHashMap的键是弱引用关联对象;HashMap是强引用关联