package mycollection;
/**
- 自定义一个HashMap
- 实现remove方法
- @author
*/
public class TestHashMap {
Node2[] table;//位桶数组 bucket array
int size;
public TestHashMap() {
table = new Node2[16];//数组长度为2的整数次幂
}
public void remove(Object key) {
Node2 up;
Node2 down;
Node2 temp;
int hash = myHash(key.hashCode(), table.length);
temp = table[hash];
int x = 0;
up = temp;
while(temp != null){
++x;
down = temp.next;
if(temp.key.equals(key)){
if(x == 1){//当被删除元素为第一个元素时
table[hash] = temp.next;
break;
}else{
up.next = down;
break;
}
}else{
up = temp;
temp = down;
}
}
}
public Object get(Object key) {
int hash = myHash(key.hashCode(), table.length);
Object value = null;
if(table[hash] != null){
Node2 temp = table[hash];
while(temp != null){
if(temp.key.equals(key)){
value = temp.value;
break;
}else{
temp = temp.next;
}
}
}
return value;
}
public void put(Object key,Object value) {
//如果要完善,还需要考虑数组扩容的问题
//定义节点对象
Node2 newNode = new Node2();
newNode.hash = myHash(key.hashCode(), table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
Node2 temp = table[newNode.hash];
Node2 iterLast = null;//正在遍历的最后一个元素
boolean keyRepeat = false;//key是否重复
if(temp == null){
//此处数组元素为空,则直接将新节点放进去
table[newNode.hash] = newNode;
size++;
}else{
//此处不为空则遍历对应链表
while(temp != null){
//判断key如果重复,覆盖
if(temp.key.equals(key)){
//System.out.println("重复了");
keyRepeat = true;
temp.value = value; //只是覆盖value值即可。 其他的值(hash,key,next)保持不变
break;
}else{
//key不重复,则遍历下一个
iterLast = temp;
temp = temp.next;
}
}
if(!keyRepeat){//没有发生重复的情况,则添加到链表的最后
iterLast.next = newNode;
size++;
}
}
}
@Override
public String toString() {
//[10:aa,20:bb]
StringBuilder sb = new StringBuilder("{");
//遍历bucket数组
for(int i = 0; i<table.length; i++){
Node2 temp = table[i];
//遍历链表
while(temp != null) {
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
sb.setCharAt(sb.length()-1, '}');
return sb.toString();
}
public static int myHash(int v,int length){
//作用一样 都是为了吧hashcode散列到 0-16 之间 值不一样
// v&(length-1) 直接位运算,效率高
// v%(length-1) 取模运算,效率低
return v&(length-1);
}
public static void main(String[] args) {
TestHashMap3 m = new TestHashMap3();
m.put(10, "a");
m.put(20, "b");
m.put(30, "c");
m.put(10, "666");
//观察debug中的 hash为5 的next
m.put(37, "d");
m.put(53, "e");//hash值为5
m.put(69, "f");//hash值为5
m.put(85, "g");//hash值为5
//通过debug功能 来观察相关功能的实现
System.out.println(m);
//找到hash值相同的元素
/*for(int i=10; i<100; i++){
System.out.println(i+"--"+myHash(i, 16));
}*/
System.out.println(m.get(69));
m.remove(37);
System.out.println(m);
}
}
#######################################################################################
package mycollection;
//HashMap
public class Node2 {
int hash;
Object key;
Object value;
Node2 next;
}