几个注意点:
Entry:内部类,填充类
loadFactor :扩展因子0.75
EMPTY_TABLE:空对象模式的使用
threshold : 阀值,就是容量乘以0.75的大小,大于就扩充
size:当前已经填充了的个数,非空个数
modCount:标识此hashmap给修改了多少次。作用在遍历过程,若出现开始值与过程中,值发现不一致。fast fail;
hashSeed
分析两个操作:put、get,其他雷同,不列
类的实例化
java.util.HashMap hashMap = new java.util.HashMap<People,String>();
点进去构造函数,参数初始化容量,加载因子赋值。其他没干啥事。
public HashMap() {
this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}
public HashMap(int initialCapacity, float loadFactor) {
if (initialCapacity < 0)
throw new IllegalArgumentException("Illegal initial capacity: " +
initialCapacity);
if (initialCapacity > MAXIMUM_CAPACITY)
initialCapacity = MAXIMUM_CAPACITY;
if (loadFactor <= 0 || Float.isNaN(loadFactor))
throw new IllegalArgumentException("Illegal load factor: " +
loadFactor);
this.loadFactor = loadFactor;
threshold = initialCapacity;
init();
}
由下面两行代码,加入一个entry;
test.People people = new test().new People();
hashMap.put(people, "1");
put方法:
触发判断是否为空。空即新建主干数组Entry<K,V>[] table;
key是否null,特殊处理,主干table0索引即null链表
key的hash再indexfor;算出位于主干数组哪里;
上面找到了主干,即链表头,遍历链表,终结条件节点不为空;
判断是否存在:key是否相等或equals,且keyhash值相等;官宣:equals改写一定要改写hashcode;为啥,因为官宣规定如果两个对象给改写成相等。
那么两个对象的hashcode值一定相等,否则就不符合规矩;
对象hashcode相等,equals可以不等。
hashcode不等,那equals肯定不等;
hashcode来自内存地址计算出来的值;
不存在,改变值加一;加入entry:先看是否扩容;再加入;
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;
}
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);
}
这里加入一个entry经典。我喜欢,这个写法;
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++;
}
get方法:是否null key,特殊处理;其他没什么特殊。就是根据上面add,hash再indexfor,在链表遍历,且key的判断方法,也就差不多。合适判断,即返回;否则返回null;
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
return null == entry ? null : entry.getValue();
}
final Entry<K,V> getEntry(Object key) {
if (size == 0) {
return null;
}
int hash = (key == null) ? 0 : 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;
}