HashMap的数据结构是数组+链表,之前的博客中有自定义的数组列表和链表,这里的数组和链表就是使用之前自定义的数组列表和链表。
实现的方法有put(K k,V v),get(K k),clear(),containsKey(K k),replace(K k,V v),remove(K k),不支持null值。
确定数组下标的方式直接用key的hashcode和数组容量进行取余运算,没有使用key.hash & (array.length-1)这种方式,道理一样,但后者效率比前者高一些。
下面是代码:
MyArrayList和MyLinkedList的实现参考之前的博客。
public class MyHashMap<K,V> {
//实际存储的key-value键值对的个数
public transient int size;
//当前数组容量
private int arrayCapacity;
//扩容判断的负载因子
private float loadFactor=0.75f;
//扩容的阈值
private int threshold;
private MyArrayList<MyLinkedList<NodeEntry>> arrayList;
private class NodeEntry{
public K key;
public V value;
public NodeEntry(K key, V value) {
super();
this.key = key;
this.value = value;
}
/**
* 重写hashCode和equals
*/
@Override
public int hashCode() {
// TODO Auto-generated method stub
return this.key.hashCode();
}
@Override
public boolean equals(Object obj) {
if(!(obj instanceof MyHashMap.NodeEntry)){
return false;
}
NodeEntry entry=(NodeEntry) obj;
return this.key.equals(entry.key)&&this.value.equals(entry.value);
}
@Override
p