实现Java hashmap

代码如下所示:
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;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值