为了更好的了解hashmap的底层结构,做了个别方法的简单实现
首先,节点,链表对象Node.java
public class Node<K,V> {
int hash;//哈希值
K key;
V value;
Node<K, V> next;//下一个节点
}
MyHashMap.java,命名有点随意了
public class MyHashMap<K,V> {
Node<K,V>[] table;
int size = 0;
public MyHashMap() {
table = new Node[16];
}
/**
* 往map中存值的方法
* @param key
* @param value
*/
public void put(K key,V value) {
Node<K, V> node = new Node<K, V>();//要添加的节点
node.hash = Myhash(key.hashCode(), table.length);
node.key = key;
node.value = value;
node.next = null;
Node<K, V> temp = table[node.hash];
if(temp != null) {
while(temp.next != null) {
if(temp.key.equals(key)){//判断是否有重复的key,如果有,则覆盖
temp.value = value;
return;
} else {
temp = temp.next;
}
}
temp.next = node;
} else {
table[node.hash] = node;
}
}
public V get(K key) {
int i = Myhash(key.hashCode(), table.length);
V value =null;
Node<K, V> getNode = table[i];
while(getNode != null) {
if(getNode.key.equals(key)) {
value = getNode.value;
break;
}
getNode = getNode.next;
}
return value;
}
public int Myhash(int v,int length) {//根据key的hashcode值来去分配位置
return v&(length -1);
}
@Override
public String toString() {
StringBuffer a = new StringBuffer("[");
Node<K, V> aaa;
for(int i = 0; i < table.length; i++){
aaa = table[i];
while(aaa != null) {
a.append(aaa.key);
a.append(":");
a.append(aaa.value+",");
aaa= aaa.next;
}
}
a.setCharAt(a.length()-1, ']');
return a.toString();
}
}
MyHashMapTest.java,新建了一个类测试了一下
public class MyHashMapTest {
public static void main(String[] args) {
MyHashMap<Integer,String> a = new MyHashMap<>();
a.put(65, "第一个节点");
a.put(59, "第二个节点");
a.put(82, "第三个节点");
a.put(81, "第四个节点");
a.put(81, "hhhhhhh");
a.put(12, "dddddd");
System.out.println(a.toString());
System.out.println(a.get(82));
}
}
哪里有不足的话,希望指出