package MyPro;
public class Node2 {
int hash;
Object key;
Object value;
Node2 next;
}
public class SxtHashMap01 {
Node2[] table;//位桶数组。bucket array
int size;//存放的键值对的个数
public SxtHashMap01() {
table = new Node2[16];//长度一般定义成2的整数幂
}
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
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;
if(temp==null) {
//此处数组元素为空,则直接将新节点放进去
table[newNode.hash] = newNode;
size++;
}else {
//此处数组元素不为空。则遍历对应链表。。
while(temp!=null) {
//判断key如果重复,则覆盖
if(temp.key.equals(key)) {
keyRepeat = true;
System.out.println("key重复了!");
temp.value = value;//只是覆盖value即可。其他的值(hash,key,next)保持不变。
break;
}else {
//key不重复,则遍历下一个
iterLast = temp;
temp = temp.next;
}
}
if(!keyRepeat) {
iterLast = newNode;
size++;
}
}
}
public static int myHash(int v,int length) {
System.out.println("hash in myHash:"+(v&(length-1)));
System.out.println("hahs in myHash:"+(v%(length-1)));
return v&(length-1);
}
@Override
public String toString() {
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 void main(String[] args) {
SxtHashMap01 m = new SxtHashMap01();
m.put(10, "aa");
m.put(20, "bb");
m.put(30, "cc");
m.put(20, "ssss");
m.put(53, "gg");
m.put(69, "hh");
m.put(85, "kk");
System.out.println(m);
// for(int i =10;i<100;i++) {
// System.out.println(i+"---"+myHash(i,16)); //53,69,85
// }
}
}
手工实现HashMap(简单版)
最新推荐文章于 2025-05-25 18:08:39 发布