1、HashMap.java
public class HashMap<V> {
private Node<V>[] arr;
private int len;
// 构造方法,初始化底层数组
public HashMap(int len){
this.len = len;
arr = new Node[len];
}
// 哈希函数(除留余数法)
private int getHash(int key){
return key%len;
}
// 添加元素(key值相同则替换value)
public void put(int key, V value){
Node<V> node = new Node<>(key, value);
int index = getHash(key);
Node<V> temp = arr[index];
if (temp == null){
arr[index] = node;
return;
}
while (temp.next != null){
temp = temp.next;
}
temp.next = node;
}
// 查找元素
public V get(int key){
int index = getHash(key);
Node<V> temp = arr[index];
while (temp!=null && temp.key!=key){
temp = temp.next;
}
return temp==null? null: temp.value;
}
// 删除元素
public boolean remove(int key){
int index = getHash(key);
Node<V> temp = arr[index];
if (temp == null){
return false;
}
// 待删除元素是首节点
if (temp.key == key){
arr[index] = temp.next;
return true;
}
// 待删除节点不是首节点
while (temp.next != null){
if (temp.next.key == key){
temp.next = temp.next.next;
return true;
}else {
temp = temp.next;
}
}
return false;
}
// 输出物理结构
public void showStruct(){
for (int i=0; i<len; ++i){
System.out.print(i + " ");
Node<V> temp = arr[i];
while (temp != null){
System.out.print("-->" + "("+ temp.key + ", " + temp.value + ")");
temp = temp.next;
}
System.out.println();
}
}
// 节点内部类
static class Node<V>{
int key;
V value;
Node next;
public Node(int key, V value) {
this.key = key;
this.value = value;
}
}
}
2、Test.java
public class Test {
public static void main(String[] args) {
HashMap<Integer> map = new HashMap<>(5);
// 添加键值对
map.put(1, 1);
map.put(2, 2);
map.put(5, 5);
map.put(7, 7);
map.put(8, 8);
map.put(10, 10);
map.put(14, 14);
map.put(18, 18);
// 输出物理结构
System.out.println("--------------------");
System.out.println("结构如下:");
map.showStruct();
// 获取指定键的值
System.out.println("--------------------");
System.out.println("键为10对应的值是:" + map.get(10));// 10
System.out.println("键为100对应的值是:" + map.get(100));// null
// 删除指定键的节点
System.out.println("--------------------");
if ( map.remove(8) ){
System.out.println("键值对删除成功,删除后的结构如下:");
map.showStruct();
}else {
System.out.println("键不存在,删除失败");
}
System.out.println("--------------------");
if ( map.remove(100) ){
System.out.println("键值对删除成功,删除后的结构如下:");
map.showStruct();
}else {
System.out.println("键不存在,删除失败");
}
}
}
3、测试结果