手写HashMap5_增加泛型
节点增加泛型
public class Node3 <K,V>{
int hash;
K key;
V value;
Node3 next;
}
主要方法代码块增加泛型
public class SxtHashMap5 <K,V>{
Node3[] table;
int size;
public SxtHashMap5() {
table = new Node3[16];
}
public void put(K key,V value) {
boolean repeat = false;
Node3 newNode = new Node3();
newNode.hash = myHash(key.hashCode(),table.length);
newNode.key = key;
newNode.value = value;
Node3 temp = table[newNode.hash];
Node3 LinkedLast = null;
if(temp==null) {
repeat = true;
table[newNode.hash] = newNode;
size++;
}else {
while(temp!=null) {
if(temp.key.equals(key)) {
temp.value = value;
}else {
LinkedLast = temp;
temp = temp.next;
}
}
}
if(!repeat) {
LinkedLast.next = newNode;
size++;
}
}
public static int myHash(int v,int length) {
return v&(length-1);
}
public static void main(String[] args) {
SxtHashMap5 map2 = new SxtHashMap5();
for(int i=0;i<50;i++) {
System.out.println(i+"---"+myHash(i, 16));
}
map2.put(17, "阿狸");
map2.put(33, "阿卡丽");
map2.put(49, "瑞雯");
System.out.println(map2);
System.out.println(map2.get(49));
System.out.println(map2.get(33));
System.out.println(map2.get(17));
}
public String toString() {
StringBuilder sb = new StringBuilder('[');
for(int i=0;i<table.length;i++) {
Node3 temp = table[i];
while(temp!=null) {
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
sb.setCharAt(sb.length()-1, ']');
return sb.toString();
}
public V get(K key) {
V value = null;
int hash = myHash(key.hashCode(),table.length);
Node3 temp = table[hash];
while(temp!=null) {
if(temp.key.equals(key)) {
value = (V)temp.value;
break;
}else {
temp = temp.next;
}
}
return value;
}
}