原始碼分析之基於LinkedList手寫HahMap(二)
阿新 • • 發佈:2018-12-06
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; } }