代码如下所示:
package com.myhashmap;
public class TestMyHashMap {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyHashMap map = new MyHashMap();
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
map.put(1, 5);
System.out.println(map.get(1));
System.out.println(map.get(2));
System.out.println(map.get(3));
System.out.println(map.get(4));
System.out.println(map.get(5));
}
}
class Node
{
private int id;
private int value;
private Node next;
public int hashcode()
{
return id;
}
public int getvalue()
{
return value;
}
public Node getNext()
{
return next;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public void setNext(Node next) {
this.next = next;
}
}
class MyHashMap
{
private int initsize = 4;
private double loadblance = 0.75;
private int size;
public Node[] nodes;
public MyHashMap()
{
nodes = new Node[initsize];
}
public void put(int id,int value)
{
Node node = new Node();
node.setId(id);
node.setValue(value);
int hashcode = node.hashcode();
hashcode = hashcode & (initsize-1);
if(nodes[hashcode] == null)
{
//如果数组没有值,则直接存储
nodes[hashcode] = node;
size++;
//判断是否需要重新调整数组大小
if(size > initsize*loadblance)
{
//重新调整
resize();
}
}
else
{
Node tmp = nodes[hashcode];
//先判断id对应的key是否已经存在
while(tmp.getId() != id && tmp.getNext() != null)
{
tmp = tmp.getNext();
}
if(tmp.getId() == id)
{
tmp.setValue(value);
return;
}
tmp.setNext(node);
}
}
public int get(int key)
{
Node node = new Node();
node.setId(key);
int hashcode = node.hashcode();
hashcode = hashcode & (initsize-1);
node = nodes[hashcode];
while(node != null)
{
if(node.getId() == key)
{
return node.getvalue();
}
node = node.getNext();
}
return 0;
}
private void resize()
{
Node[] tmpnodes = new Node[initsize*2];
for(int i=0; i < initsize;i++)
{
Node tmp = nodes[i];
//循环重组原数组的每一个元素
while (tmp != null)
{
int hashcode = tmp.hashcode();
//获得在新数组中的位置
hashcode = hashcode & (2*initsize-1);
if(tmpnodes[hashcode] == null)
{
//如果没有元素,则直接放入
tmpnodes[hashcode] = tmp;
}
else
{
Node node = tmpnodes[hashcode];
if(node.getNext() != null)
{
node = node.getNext();
}
node.setNext(tmp);
}
tmp = tmp.getNext();
}
}
initsize = initsize*2;
nodes = tmpnodes;
}
}