- 定义接口
package com.lzq.MapInterface;
public interface Map<K,V> {
//存储
V put(K k, V v);
//获取
V get(K k);
//移除
V remove(K k);
}
- 编写Entry类
package com.lzq.HashMap;
public class Entry<K,V> {
K k;
V v;
Entry<K,V> next;
public Entry(K k, V v, Entry<K, V> next) {
this.k = k;
this.v = v;
this.next = next;
}
}
编写HashMap类
package com.lzq.HashMap;
import com.lzq.MapInterface.Map;
public class HashMap<K,V> implements Map<K,V> {
//定义初始默认的长度
final static int DEFAULT_CAPACITY = 16;
//定义目前已经存储的内容大小
int size = 0;
//定义数组
Entry<K,V>[] table = null;
//初始构造方法
public HashMap() {
table = new Entry[DEFAULT_CAPACITY];
}
@Override
public V put(K k,V v) {
//通过hashcode % 数组长度 计算下标。
int index = k.hashCode() % (table.length-1);
//拿到数组当前下标值
Entry<K,V> current = table[index];
//如果下标值有数据
if(current != null){
//对比key是否是相同的,如果是相同的那么就覆盖value,如果不同那么就在链表后面增加。
while(current != null){
if(current.k == v){
V oldValue = current.v;
current.v = v;
return oldValue;
}
current = current.next;
}
//链表中没有相同的元素,采用头插法,直接插在头部
table[index] = new Entry<K,V>(k,v,table[index]);
}
//数组当前位置没有内容,直接插入
table[index] = new Entry<K,V>(k,v,null);
size ++;
return null;
}
@Override
public V get(K k) {
//通过key获取下标
int index = k.hashCode() % (table.length - 1);
//通过index拿到table数组的值
Entry<K,V> current = table[index];
//遍历链表
while(current != null){
if(current.k == k){
return current.v;
}
current = current.next;
}
return null;
}
@Override
public V remove(K k) {
int index = k.hashCode() % (table.length - 1);
Entry<K, V> current = table[index];
// 如果直接匹配第一个节点
if(current.k == k){
table[index] = null;
size--;
return current.v;
}
// 在链表中删除节点
while(current.next != null){
if(current.next.k == k){
V oldValue = current.next.v;
current.next = current.next.next;
size--;
return oldValue;
}
current = current.next;
}
return null;
}
}
- 测试
@Test
public void testHashMap(){
HashMap hashMap = new HashMap();
hashMap.put("1","lu");
System.out.println("=======" + hashMap.get("1"));
hashMap.put("2","ze");
System.out.println("=======" + hashMap.get("2"));
hashMap.put("3","quan");
System.out.println("=======" + hashMap.get("3"));
hashMap.put("1","lzq");
System.out.println("=======" + hashMap.get("1"));
hashMap.remove("1");
System.out.println("=======" + hashMap.get("1"));
}