简单实现HashMap,对理解HashMap很有帮助

为了更好的了解hashmap的底层结构,做了个别方法的简单实现
在这里插入图片描述
首先,节点,链表对象Node.java

public class Node<K,V> {
	int hash;//哈希值
	K key;
	V value;
	Node<K, V> next;//下一个节点
}

MyHashMap.java,命名有点随意了

public class MyHashMap<K,V> {
	Node<K,V>[] table;
	int size = 0;
	public MyHashMap() {
		table = new Node[16];
	}
	/**
	 * 往map中存值的方法
	 * @param key 
	 * @param value
	 */
	public void put(K key,V value) {
		Node<K, V> node = new Node<K, V>();//要添加的节点
		node.hash = Myhash(key.hashCode(), table.length);
		node.key = key;
		node.value = value;
		node.next = null;
		Node<K, V> temp = table[node.hash];
		if(temp != null) {
			while(temp.next != null) {
				if(temp.key.equals(key)){//判断是否有重复的key,如果有,则覆盖
					temp.value = value;
					return;
				} else {
					temp = temp.next;
				}	
			}
			temp.next = node;
		} else {
			table[node.hash] = node; 
		}
	}
	public V get(K key) {
		int i = Myhash(key.hashCode(), table.length);
		V value =null;
		Node<K, V> getNode = table[i];
		while(getNode != null) {
			if(getNode.key.equals(key)) {
				value = getNode.value;
				break;
			}
			getNode = getNode.next;
		}
		return value;
	}
	public int Myhash(int v,int length) {//根据key的hashcode值来去分配位置
		return v&(length -1);
	}
	@Override
	public String toString() {
		StringBuffer a = new StringBuffer("[");
		Node<K, V> aaa;
		for(int i = 0; i < table.length; i++){
			aaa = table[i];
			while(aaa != null) {
				a.append(aaa.key);
				a.append(":");
				a.append(aaa.value+",");
				aaa= aaa.next;
			}
			
		}
		a.setCharAt(a.length()-1, ']');
		return a.toString();
	}
}

MyHashMapTest.java,新建了一个类测试了一下

public class MyHashMapTest {
	public static void main(String[] args) {
		MyHashMap<Integer,String> a = new MyHashMap<>();
		a.put(65, "第一个节点");
		a.put(59, "第二个节点");
		a.put(82, "第三个节点");
		a.put(81, "第四个节点");
		a.put(81, "hhhhhhh");
		a.put(12, "dddddd");
		System.out.println(a.toString());
		System.out.println(a.get(82));
	}
}

哪里有不足的话,希望指出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值