/**
* 自定义简单HashMap
*
* @author 孙昊
*/
public class ShHashMap<K,V> {
Node<K,V>[] table;//位桶数组
int size;//存放键值对个数
//构造方法:定义一个长度为16的数组(长度需要是2的整数次幂,按位与的散列算法需要这样的条件)
public ShHashMap(){
table = new Node[16];//长度一般定义成2的整数次幂。
}
/**
* 插入方法
*
* @author 孙昊
*/
public void put(K k, V v) {
//如果要完善还要考虑数组扩容的问题
//定义一个新的Node对象,存储参数传入的K-V
Node<K,V> newNode = new Node<>();
newNode.hash = hash(k.hashCode(),table.length);
newNode.key = k;
newNode.value = v;
newNode.next = null;
//temp为table数组中 插入的key的hash对应位置的Node
Node<K,V> temp = table[newNode.hash];
//遍历后的最后一个元素
Node<K,V> iterLast = null;
if(temp==null) {
//此处数组元素为空,则将新节点直接存入该位桶数组。
table[newNode.hash] = newNode;
}else {
//此处数组元素不为空,则要遍历对应链表,查看是否有相同的key?若有,则覆盖当前value;若没有,则链表长度+1;
while(temp!=null) {
//如果key相同
if(temp.key.equals(k)) {
temp.value = v;
//替换后则结束本方法。
return;
}
//如果key不同则继续循环
//循环条件
iterLast = temp;
temp = temp.next;
}
//若果temp==null,则在temp的前一个位置,插入对应的节点。
iterLast.next = newNode;
}
size++;
}
/**
* 获取方法
*
* @author 孙昊
*/
public V get(K key) {
V v = null;
Node<K,V> temp;
if((temp = table[hash(key.hashCode(),table.length)])!=null) {
while(temp!=null) {
if(key.equals(temp.key)) {
v = temp.value;
return v;
}
temp = temp.next;
}
}
return v;
}
/**
* 删除节点并打印节点value方法
*
* @author 孙昊
*/
public V remove(K k) {
V v = null;
Node<K,V> temp;
Node<K,V> flag = null;
if((temp=table[hash(k.hashCode(),table.length)])!=null) {
if(k.equals(temp.key)) {
v = temp.value;
table[hash(k.hashCode(),table.length)]=temp.next;
return v;
}
while(temp!=null) {
if(k.equals(temp.key)) {
flag.next = temp.next;
return temp.value;
}
flag = temp;
temp = temp.next;
}
}
return v;
}
/**
* 散列算法
*
* @author 孙昊
*/
public int hash(int hashcode,int length) {
return hashcode&(length-1);
}
/**
* 重写toString方法
*
* @author 孙昊
*/
public String toString() {
//{key1:value1,key2:value2....}
StringBuilder sb = new StringBuilder("{");
for(int i=0; i<table.length; i++) {
Node<K,V> temp = table[i];
while(temp!=null) {
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
return sb.substring(0,sb.length()-1)+"}";
}
}
手写简易HashMap
最新推荐文章于 2021-04-30 04:08:40 发布