public class WhalesonMap<K,V> { Entry<K,V> [] tab; private int CAPACITY = 1 << 4;//6 @AllArgsConstructor @NoArgsConstructor @Data public class Entry<K,V>{ private K key; private V value; private Entry<K,V> next; } public void put(K key, V value){ if(tab == null){ initialize(); } int keyHashCode = toHash( key ); int index = indexFor(keyHashCode); for (Entry<K,V> entry = tab[index]; entry != null; entry = entry.next){ if(entry.key.equals(key)){ entry.key = key; } } addEntry(key,value,index); } public V get(K k){ int hash = toHash(k); int index = indexFor(hash); Entry<K,V> tempEntry = tab[index]; if(tempEntry == null){ throw new NullPointerException("No exist k in tab"); } return tempEntry.getValue(); } private void addEntry(K key, V value, int index) { Entry<K,V> entry = new Entry<>(key,value,tab[index]); tab[index] = entry; } private int indexFor(int keyHashCode) { //也可以用数组长度取模 return keyHashCode % tab.length ; } public void initialize(){ tab = new Entry[CAPACITY]; } public int toHash(K k){ return k.hashCode(); } }
自己写一个Map
最新推荐文章于 2024-04-28 08:59:39 发布