源码分析之基于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;
	}

}

猜你喜欢

转载自blog.csdn.net/qq_41988225/article/details/84824427