HashMap1.7
package JDK17HashMap;
import static java.lang.Math.pow;
public class WZFHashMap<K extends Comparable<K>,V>
{
private static final int ARRNUM = 10;
private int arrsNum =0;
private Node nodes[];
public WZFHashMap(int arrsCapacity)
{
this.nodes = new Node[arrsCapacity];
this.arrsNum=arrsCapacity;
}
public WZFHashMap()
{
this.nodes = new Node[ARRNUM];
}
public void insertNode(K key,V value)
{
if(this.nodes == null)
{
throw new RuntimeException ("初始化失败!");
}
Node node = new Node (key, value,null);
if(node == null)
{
throw new RuntimeException ("Node节点初始化失败!");
}
if(key == null)
{
selectInsertPosition (0,node);
}
else
{
int hash = hash (key);
selectInsertPosition (hash,node);
}
}
private void selectInsertPosition(int hash,Node node)
{
Node p = nodes[hash];
if(p == null)
{
nodes[hash]=node;
return;
}
Node prior = null;
while (p!=null)
{
prior = p;
p=p.next;
}
prior.next = node;
}
private int getArrnum()
{
return this.arrsNum == 0 ? ARRNUM : arrsNum;
}
private int hash(K key)
{
int num;
if(arrsNum != 0)
{
num = key.hashCode () % arrsNum;
}
else
{
num = key.hashCode () % ARRNUM;
}
return num;
}
public void printHashMap()
{
for(int i =0;i<getArrnum ();i++)
{
System.out.println ("**************************");
Node p =nodes[i];
while (p != null)
{
System.out.println ("key:"+p.key+" value:"+p.value);
p=p.next;
}
System.out.println ("**************************");
}
}
static class Node<K extends Comparable<K>,V>
{
private K key;
private V value;
private Node next;
public Node(K key, V value,Node node)
{
this.key = key;
this.value = value;
this.next = node;
}
public Node()
{
}
public Node getNext()
{
return next;
}
public void setNext(Node next)
{
this.next = next;
}
public K getKey()
{
return key;
}
public void setKey(K key)
{
this.key = key;
}
public V getValue()
{
return value;
}
public void setValue(V value)
{
this.value = value;
}
}
}
测试类
package JDK17HashMap;
import java.util.HashMap;
public class HashTest
{
public static void main(String[] args)
{
WZFHashMap<Integer, String> map = new WZFHashMap<> (3);
map.insertNode (2,"美国");
map.insertNode (1,"中国");
map.insertNode (3,"英国");
map.insertNode (2,"俄罗斯");
map.insertNode (2,"日本");
map.insertNode (1,"太平洋");
map.insertNode (3,"法国");
map.insertNode (3,"你好");
map.printHashMap ();
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210315172719754.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzU2NDcyOA==,size_16,color_FFFFFF,t_70)