package cn.java.mhz;
/**
* 自定义实现HashMap
* 数组和链表的组合形式,数组查找快,链表增加和删除速度快,所以HashMap综合了两方面的优势
* 在JDK8以后,在每条链中加入了红黑树的处理,这使得查询效率进一步提高
* @author asus
*
*/
public class MyHashMap<K,V> {
class Node<K,V>{
public int hash;
public K key;
public V value;
public Node next;
}
Node[] table; //位桶数组
int size; //存放键值对的个数
public MyHashMap()
{
table = new Node[16];
}
//增加HashMap元素 如果要变得更完美,那么需要考虑数组扩容的操作,避免算法的复杂度退化
public void put(K key,V value)
{
Node newnode = new Node();
newnode.hash= myHash(key.hashCode(),table.length);
newnode.key = key;
newnode.value = value;
newnode.next = null;
Node temp = new Node();
temp = table[newnode.hash];
//当是头结点的时候
if(temp==null) {
table[newnode.hash] = newnode;
}
else {
//如果key值重复,那么需要覆盖原来的value值,如果发现并不重复,那么在原来的链表后添加此元素即可
//则在链表后添加此数据
Node last = new Node();
last = temp;
while(temp!=null)
{
if(temp.key.equals(key)) {
temp.value = value;
break;
}
temp = temp.next;
if(temp!=null) last = temp;
}
if(temp==null) {
last.next = newnode;
}
}
}
//查询HahsmMap元素 给定key值,求value值
public V get(K Key)
{
Node newnode = new Node();
newnode=table[myHash(Key.hashCode(),table.length)];
boolean flag=false;
if(newnode==null) {
return null;
}
else {
Node temp = new Node();
temp = newnode;
while(temp!=null)
{
if(temp.key.equals(Key)) {
flag=true;
return (V)temp.value;
}
temp = temp.next;
}
if(!flag) return null;
}
return null;
}
//移除操作,根据key值进行移除
public boolean remove(Object Key)
{
boolean flag=false;
//如果查询失败,那么移除必然失败
if(get((K)Key)==null) {
return false;
}
else {
Node newnode = new Node();
newnode = table[myHash(Key.hashCode(),table.length)];
int index=0;
Node last =new Node();
last = newnode;
while(newnode!=null)
{
if(newnode.key.equals(Key)) {
Node NextNode = new Node();
NextNode = newnode.next;
if(index==0) {
if(NextNode==null) {
table[newnode.hash] = null;
}
else {
table[newnode.hash] = NextNode;
}
}
else {
if(NextNode==null) {
last.next=null;
}
else {
last.next = NextNode;
}
}
break;
}
index++;
last = newnode;
newnode = newnode.next;
}
return true;
}
}
//返回Hash值
public static int myHash(int v,int length)
{
return v&(length-1);
}
//重写toString方法
@Override
public String toString()
{
StringBuilder str = new StringBuilder();
Node newnode = new Node();
for(int i=0; i<table.length;i++)
{
if(table[i]==null) continue;
newnode = table[i];
while(newnode!=null) {
str.append("["+newnode.key+","+newnode.value+"] ");
newnode=newnode.next;
}
str.append("\n");
}
return str.toString();
}
public static void main(String[] args)
{
MyHashMap<Integer,String> m = new <Integer,String>MyHashMap();
m.put(10, "aa");
m.put(20, "bb");
m.put(30, "cc");
m.put(20, "xx");
m.put(36,"cc");
m.put(50, "mhz");
System.out.printf(m.toString());
System.out.println(m.get(36));
System.out.println(m.get(20));
m.remove(20);
System.out.printf(m.toString());
System.out.println();
m.remove(36);
System.out.printf(m.toString());
}
}