源码分析之基于LinkedList手写HahMap(二)

package com.mayikt.extLinkedListHashMap;

import java.util.LinkedList;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 基於linkedList實現hashMap
 * 
 * @author zjmiec
 *
 */
@SuppressWarnings("unchecked")
public class LinkedListHashMap {

	LinkedList<Entry>[] tables = new LinkedList[998];

	// 添加
	@SuppressWarnings("rawtypes")
	public void put(Object key, Object value) {
		Entry newEntry = new Entry(key, value);
		int hash = getHash(key);
		LinkedList<Entry> entryLinkedList = tables[hash];
		if (entryLinkedList == null) {
			// 没有hash冲突
			entryLinkedList = new LinkedList<Entry>();
			entryLinkedList.add(newEntry);
			tables[hash] = entryLinkedList;
		} else {
			// 发生了hash冲突
			for (Entry entry : entryLinkedList) {
				if (entry.key.equals(key)) {
					entry.value = value;
					// entryLinkedList.add(entry);
				} else {
					// hashCode相同,对象值不一定相同
					entryLinkedList.add(newEntry);
				}
			}

		}
	}

	// 获取
	public Object get(Object key) {
		int hash = getHash(key);
		LinkedList<Entry> linkedList = tables[hash];
		for (Entry entry : linkedList) {
			if (entry.key.equals(key)) {
				return entry.value;
			}
		}
		return null;
	}

	private int getHash(Object key) {
		int hashCode = key.hashCode();
		// hash取模
		return hashCode % tables.length;

	}

	public static void main(String[] args) {

		LinkedListHashMap linkedListHashMap = new LinkedListHashMap();
		linkedListHashMap.put("a", "aa");
		linkedListHashMap.put("a", "vvvv");

		System.out.println(linkedListHashMap.get("a"));

		// System.out.println(2 % 13);
	}
}

// hash存储对象
class Entry<Key, Value> {
	Key key;// hashmap集合的key
	Value value;// hashmap集合的value

	public Entry(Key key, Value value) {
		super();
		this.key = key;
		this.value = value;
	}

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值