原始碼分析之基於ArrayList手寫HahMap(一)
阿新 • • 發佈:2018-12-06
import java.util.ArrayList; import java.util.List; /** * 基於arraylist實現hashmap集合(簡版:效率低) * @author zjmiec * */ public class ExtArrayListHashMap<Key, Value> { // map容器 List<Entry<Key, Value>> tables = new ArrayList<>(); int size; // put public void put(Key key, Value value) { Entry<Key, Value> entery = getEntry(key); if (entery != null) { entery.value=value; } else { Entry<Key, Value> newEntery = new Entry<Key, Value>(key, value); tables.add(newEntery); } size = tables.size(); } public Value get(Key key) { Entry<Key, Value> entry = getEntry(key); return entry == null ? null : entry.value; } public Entry<Key, Value> getEntry(Key key) { for (Entry<Key, Value> entry : tables) { if (entry.key.equals(key)) { return entry; } } return null; } public int getSize() { return tables.size(); } public static void main(String[] args) { ExtArrayListHashMap<String, String> extArrayListHashMap = new ExtArrayListHashMap<String, String>(); extArrayListHashMap.put("a", "aa"); extArrayListHashMap.put("b", "bb"); extArrayListHashMap.put("c", "cc"); extArrayListHashMap.put("c", "dd"); System.out.println(extArrayListHashMap.get("c")); //System.out.println(extArrayListHashMap.size); /* * String str = (String) extArrayListHashMap.get("a"); * System.out.println(str); */ } } // 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; } }