public class Node<K, V> {
int hash;
K key;
V value;
Node<K, V> next;
}
public class WhHashMap<K, V> {
Node<K, V>[] table; // 位桶数组
int size;
@SuppressWarnings("unchecked")
public WhHashMap() {
table = new Node[16];
}
public void put(K key, V value) {
Node<K, V> newNode = new Node<K, V>();
newNode.hash = myHash(key.hashCode(), table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
Node<K, V> temp = table[newNode.hash];
Node<K, V> last = null;
boolean keyRepeat = false;
if (temp == null) {
table[newNode.hash] = newNode; // 第一个位桶元素为空时,新节点直接放入
size++;
} else {
// 遍历链表:如果重复,则覆盖,如果不重复,则追加到链表尾部
while (temp != null) {
// 如果重复,则覆盖值
if (temp.key.equals(key)) {
keyRepeat = true;
temp.value = value;
break;
} else {
// 如果不重复,则追加到链表尾部
last = temp;
temp = temp.next;
}
}
if (!keyRepeat) { // 如果key不重复,则添加到链表最后
last.next = newNode;
size++;
} else {
}
}
}
public int myHash(int v, int length) {
// System.out.println("put-hash:" + (v & (length - 1)));
return v & (length - 1);
}
// 增加get方法
@SuppressWarnings("unchecked")
public V get(K key) {
int hash = myHash(key.hashCode(), table.length);
V value = null;
if (table[hash] != null) {
Node<?, ?> temp = table[hash];
while (temp != null) {
if (temp.key.equals(key)) {
value = (V)temp.value;
break;
} else {
temp = temp.next;
}
}
}
return value;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("{");
// 遍历数组
for (int i = 0; i < table.length; i++) {
// 遍历链表
Node<K, V> temp = table[i];
// TODO
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) {
WhHashMap<Integer, String> map = new WhHashMap<Integer, String>();
map.put(10, "aa"); // 10
map.put(20, "bb"); // 4
map.put(30, "cc"); // 14
map.put(10, "AA"); // 10
map.put(4, "yyy"); // 4
map.put(36, "7777"); // 4
System.out.println(map.toString());
System.out.println("map size:" + map.size);
System.out.println(map.get(10));
System.out.println(map.get(1));
System.out.println(map.get(36));
}
}