节点类:
package 容器;
public class Node3 {
int hash;
K key;
V value;
Node3 next;
}
主类:
package 容器;
public class 测试14自定义实现HashMap类02 {
Node3[] table; //位桶数组
int size;//存储此类实际存储元素的多少
public 测试14自定义实现HashMap类02() {
table = new Node3[16]; //定义为2的整数次幂,如同ArrayList一样,需要考虑数组扩容问题
}
public void put(K key,V value) {
Node3 newNode = new Node3();
newNode.hash = myHash(key.hashCode(), table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
Node3 temp = table[newNode.hash];
Node3 iterLast = null;//为了保存接下来遍历后的最后一个元素
boolean keyRepeat = false;
//遗留代码,如果要完善,考虑数组扩容的问题
if (temp == null) {
//数组为空,直接存在第一个位置
table[newNode.hash] = newNode;
size ++;
}else {
//数组不为空,需要遍历对应的链表
while (temp != null) {
//key重复则覆盖
if (temp.key.equals(key)) {
System.out.println("key重复,将要执行覆盖操作。");
//只是覆盖value即可,其他的值(hash、key、next)都保持不变
temp.value = value;
keyRepeat = true;
break;
}else {
iterLast = temp;
//不重复的话,继续遍历往下
temp = temp.next;
}
}
if (!keyRepeat) {
//因为没有发生key覆盖,next不需要改变
iterLast.next = newNode;
size ++;
}
}
}
public V get(int key) {
int hash = myHash(key,table.length);
V value = null;
if (table[hash] != null) {
Node3 temp = table[hash];
while(temp != null) {
if (temp.key.equals(key)) {
value = (V)temp.value;
break;
}
temp = temp.next;
}
}
return value;
}
public int myHash(int v,int l) {
//System.out.println(v&(l - 1));
return v&(l - 1);
}
@Override
public String toString() {
//应该达成的效果:{1:ceshi1,2:ceshi2}
StringBuilder sbu = new StringBuilder("{") ;
//遍历数组
for (int i = 0; i < table.length; i++) {
Node3 temp = table[i];
if(table[i] != null) {
sbu.append("["+"桶"+i+"---> ");
}
//遍历链表
while (temp != null) {
sbu.append(temp.key + ":" + temp.value + ",");
temp = temp.next;
}
sbu.setCharAt(sbu.length() - 1, '}');
if(table[i] != null) {
sbu.append("]");
}
}
return sbu.toString();
}
public static void main(String[] args) {
测试14自定义实现HashMap类02 h2 = new 测试14自定义实现HashMap类02<>();
h2.put(1,"ceshi1");
h2.put(17,"ceshi3");
h2.put(2,"ceshi2");
h2.put(2,"ceshi12");
h2.put(32,"ceshi14");
System.out.println(h2);
System.out.println(h2.get(17));
}
}
测试: