package com.hcy.collection;
class Node2{
int hash;
Object key;
Object value;
Node2 next;
public Node2() {
super();
}
/*public Node(int hash, Object key, Object value, Node next) {
super();
this.hash = hash;
this.key = key;
this.value = value;
this.next = next;
}*/
}
public class MyHashMap {
private Node2[] table;
private int size;
public MyHashMap() {
super();
table = new Node2[16];
size = 0;
}
public int size(){
return size;
}
public void put(Object key,Object value){
Node2 newNode = new Node2();
newNode.hash = myhash(key, table.length);
newNode.key = key;
newNode.value = value;
newNode.next = null;
boolean keyReap = false;
Node2 temp = table[newNode.hash];
Node2 iterLast = null;//存放最后一个节点
//数组此处为空,直接放入
if(temp == null){
table[newNode.hash] = newNode;
size++;
}else{ //table此处位置不为空,将节点加到链表中
while(temp != null){
if(temp.key.equals(key)){//键值重复
keyReap = true;
temp.value = value;
break;
}
iterLast = temp;
temp = temp.next;
}
if(!keyReap){//键值不重复,将节点加到链表末尾
iterLast.next = newNode;
size++;
}
}
}
public Object get(Object key){
Node2 temp = null;
int i = myhash(key, table.length);
temp = table[i];//找到位桶中对应的链表
while(temp != null){//进行遍历
if(temp.key.equals(key)){//找到键对应的值
return temp.value;
}
temp = temp.next;
}
return null;//没有找到键对应的值
}
@Override
public String toString() {
StringBuffer sb = new StringBuffer("{");
Node2 temp = null;
for(int i=0;i<table.length;i++){
temp = table[i];
while(temp!=null){
sb.append(temp.key+":"+temp.value+",");
temp = temp.next;
}
}
sb.setCharAt(sb.length()-1,'}');
return sb.toString();
}
public int myhash(Object key,int length){
return key.hashCode() & (length-1);
}
public static void main(String[] args) {
MyHashMap map = new MyHashMap();
map.put(1, "aa");
map.put(2, "bb");
map.put(3, "cc");
map.put(2, "kk");
Object temp = map.get(2);
System.out.println(map);
System.out.println(temp);
}
}