1. 程式人生 > >Java 集合系列11之 Hashtable詳細介紹(原始碼解析)和使用示例

Java 集合系列11之 Hashtable詳細介紹(原始碼解析)和使用示例

  1 package java.util;
  2 import java.io.*;
  3 
  4 public class Hashtable<K,V>
  5     extends Dictionary<K,V>
  6     implements Map<K,V>, Cloneable, java.io.Serializable {
  7 
  8     // Hashtable儲存key-value的陣列。
  9     // Hashtable是採用拉鍊法實現的,每一個Entry本質上是一個單向連結串列
 10     private
transient Entry[] table; 11 12 // Hashtable中元素的實際數量 13 private transient int count; 14 15 // 閾值,用於判斷是否需要調整Hashtable的容量(threshold = 容量*載入因子) 16 private int threshold; 17 18 // 載入因子 19 private float loadFactor; 20 21 // Hashtable被改變的次數 22 private transient
int modCount = 0; 23 24 // 序列版本號 25 private static final long serialVersionUID = 1421746759512286392L; 26 27 // 指定“容量大小”和“載入因子”的建構函式 28 public Hashtable(int initialCapacity, float loadFactor) { 29 if (initialCapacity < 0) 30 throw new IllegalArgumentException("Illegal Capacity: "+ 31
initialCapacity); 32 if (loadFactor <= 0 || Float.isNaN(loadFactor)) 33 throw new IllegalArgumentException("Illegal Load: "+loadFactor); 34 35 if (initialCapacity==0) 36 initialCapacity = 1; 37 this.loadFactor = loadFactor; 38 table = new Entry[initialCapacity]; 39 threshold = (int)(initialCapacity * loadFactor); 40 } 41 42 // 指定“容量大小”的建構函式 43 public Hashtable(int initialCapacity) { 44 this(initialCapacity, 0.75f); 45 } 46 47 // 預設建構函式。 48 public Hashtable() { 49 // 預設建構函式,指定的容量大小是11;載入因子是0.75 50 this(11, 0.75f); 51 } 52 53 // 包含“子Map”的建構函式 54 public Hashtable(Map<? extends K, ? extends V> t) { 55 this(Math.max(2*t.size(), 11), 0.75f); 56 // 將“子Map”的全部元素都新增到Hashtable中 57 putAll(t); 58 } 59 60 public synchronized int size() { 61 return count; 62 } 63 64 public synchronized boolean isEmpty() { 65 return count == 0; 66 } 67 68 // 返回“所有key”的列舉物件 69 public synchronized Enumeration<K> keys() { 70 return this.<K>getEnumeration(KEYS); 71 } 72 73 // 返回“所有value”的列舉物件 74 public synchronized Enumeration<V> elements() { 75 return this.<V>getEnumeration(VALUES); 76 } 77 78 // 判斷Hashtable是否包含“值(value)” 79 public synchronized boolean contains(Object value) { 80 // Hashtable中“鍵值對”的value不能是null, 81 // 若是null的話,丟擲異常! 82 if (value == null) { 83 throw new NullPointerException(); 84 } 85 86 // 從後向前遍歷table陣列中的元素(Entry) 87 // 對於每個Entry(單向連結串列),逐個遍歷,判斷節點的值是否等於value 88 Entry tab[] = table; 89 for (int i = tab.length ; i-- > 0 ;) { 90 for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) { 91 if (e.value.equals(value)) { 92 return true; 93 } 94 } 95 } 96 return false; 97 } 98 99 public boolean containsValue(Object value) { 100 return contains(value); 101 } 102 103 // 判斷Hashtable是否包含key 104 public synchronized boolean containsKey(Object key) { 105 Entry tab[] = table; 106 int hash = key.hashCode(); 107 // 計算索引值, 108 // % tab.length 的目的是防止資料越界 109 int index = (hash & 0x7FFFFFFF) % tab.length; 110 // 找到“key對應的Entry(連結串列)”,然後在連結串列中找出“雜湊值”和“鍵值”與key都相等的元素 111 for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { 112 if ((e.hash == hash) && e.key.equals(key)) { 113 return true; 114 } 115 } 116 return false; 117 } 118 119 // 返回key對應的value,沒有的話返回null 120 public synchronized V get(Object key) { 121 Entry tab[] = table; 122 int hash = key.hashCode(); 123 // 計算索引值, 124 int index = (hash & 0x7FFFFFFF) % tab.length; 125 // 找到“key對應的Entry(連結串列)”,然後在連結串列中找出“雜湊值”和“鍵值”與key都相等的元素 126 for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { 127 if ((e.hash == hash) && e.key.equals(key)) { 128 return e.value; 129 } 130 } 131 return null; 132 } 133 134 // 調整Hashtable的長度,將長度變成原來的(2倍+1) 135 // (01) 將“舊的Entry陣列”賦值給一個臨時變數。 136 // (02) 建立一個“新的Entry陣列”,並賦值給“舊的Entry陣列” 137 // (03) 將“Hashtable”中的全部元素依次新增到“新的Entry陣列”中 138 protected void rehash() { 139 int oldCapacity = table.length; 140 Entry[] oldMap = table; 141 142 int newCapacity = oldCapacity * 2 + 1; 143 Entry[] newMap = new Entry[newCapacity]; 144 145 modCount++; 146 threshold = (int)(newCapacity * loadFactor); 147 table = newMap; 148 149 for (int i = oldCapacity ; i-- > 0 ;) { 150 for (Entry<K,V> old = oldMap[i] ; old != null ; ) { 151 Entry<K,V> e = old; 152 old = old.next; 153 154 int index = (e.hash & 0x7FFFFFFF) % newCapacity; 155 e.next = newMap[index]; 156 newMap[index] = e; 157 } 158 } 159 } 160 161 // 將“key-value”新增到Hashtable中 162 public synchronized V put(K key, V value) { 163 // Hashtable中不能插入value為null的元素!!! 164 if (value == null) { 165 throw new NullPointerException(); 166 } 167 168 // 若“Hashtable中已存在鍵為key的鍵值對”, 169 // 則用“新的value”替換“舊的value” 170 Entry tab[] = table; 171 int hash = key.hashCode(); 172 int index = (hash & 0x7FFFFFFF) % tab.length; 173 for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) { 174 if ((e.hash == hash) && e.key.equals(key)) { 175 V old = e.value; 176 e.value = value; 177 return old; 178 } 179 } 180 181 // 若“Hashtable中不存在鍵為key的鍵值對”, 182 // (01) 將“修改統計數”+1 183 modCount++; 184 // (02) 若“Hashtable實際容量” > “閾值”(閾值=總的容量 * 載入因子) 185 // 則調整Hashtable的大小 186 if (count >= threshold) { 187 // Rehash the table if the threshold is exceeded 188 rehash(); 189 190 tab = table; 191 index = (hash & 0x7FFFFFFF) % tab.length; 192 } 193 194 // (03) 將“Hashtable中index”位置的Entry(連結串列)儲存到e中 195 Entry<K,V> e = tab[index]; 196 // (04) 建立“新的Entry節點”,並將“新的Entry”插入“Hashtable的index位置”,並設定e為“新的Entry”的下一個元素(即“新Entry”為連結串列表頭)。 197 tab[index] = new Entry<K,V>(hash, key, value, e); 198 // (05) 將“Hashtable的實際容量”+1 199 count++; 200 return null; 201 } 202 203 // 刪除Hashtable中鍵為key的元素 204 public synchronized V remove(Object key) { 205 Entry tab[] = table; 206 int hash = key.hashCode(); 207 int index = (hash & 0x7FFFFFFF) % tab.length; 208 // 找到“key對應的Entry(連結串列)” 209 // 然後在連結串列中找出要刪除的節點,並刪除該節點。 210 for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) { 211 if ((e.hash == hash) && e.key.equals(key)) { 212 modCount++; 213 if (prev != null) { 214 prev.next = e.next; 215 } else { 216 tab[index] = e.next; 217 } 218 count--; 219 V oldValue = e.value; 220 e.value = null; 221 return oldValue; 222 } 223 } 224 return null; 225 } 226 227 // 將“Map(t)”的中全部元素逐一新增到Hashtable中 228 public synchronized void putAll(Map<? extends K, ? extends V> t) { 229 for (Map.Entry<? extends K, ? extends V> e : t.entrySet()) 230 put(e.getKey(), e.getValue()); 231 } 232 233 // 清空Hashtable 234 // 將Hashtable的table陣列的值全部設為null 235 public synchronized void clear() { 236 Entry tab[] = table; 237 modCount++; 238 for (int index = tab.length; --index >= 0; ) 239 tab[index] = null; 240 count = 0; 241 } 242 243 // 克隆一個Hashtable,並以Object的形式返回。 244 public synchronized Object clone() { 245 try { 246 Hashtable<K,V> t = (Hashtable<K,V>) super.clone(); 247 t.table = new Entry[table.length]; 248 for (int i = table.length ; i-- > 0 ; ) { 249 t.table[i] = (table[i] != null) 250 ? (Entry<K,V>) table[i].clone() : null; 251 } 252 t.keySet = null; 253 t.entrySet = null; 254 t.values = null; 255 t.modCount = 0; 256 return t; 257 } catch (CloneNotSupportedException e) { 258 // this shouldn't happen, since we are Cloneable 259 throw new InternalError(); 260 } 261 } 262 263 public synchronized String toString() { 264 int max = size() - 1; 265 if (max == -1) 266 return "{}"; 267 268 StringBuilder sb = new StringBuilder(); 269 Iterator<Map.Entry<K,V>> it = entrySet().iterator(); 270 271 sb.append('{'); 272 for (int i = 0; ; i++) { 273 Map.Entry<K,V> e = it.next(); 274 K key = e.getKey(); 275 V value = e.getValue(); 276 sb.append(key == this ? "(this Map)" : key.toString()); 277 sb.append('='); 278 sb.append(value == this ? "(this Map)" : value.toString()); 279 280 if (i == max) 281 return sb.append('}').toString(); 282 sb.append(", "); 283 } 284 } 285 286 // 獲取Hashtable的列舉類物件 287 // 若Hashtable的實際大小為0,則返回“空列舉類”物件; 288 // 否則,返回正常的Enumerator的物件。(Enumerator實現了迭代器和列舉兩個介面) 289 private <T> Enumeration<T> getEnumeration(int type) { 290 if (count == 0) { 291 return (Enumeration<T>)emptyEnumerator; 292 } else { 293 return new Enumerator<T>(type, false); 294 } 295 } 296 297 // 獲取Hashtable的迭代器 298 // 若Hashtable的實際大小為0,則返回“空迭代器”物件; 299 // 否則,返回正常的Enumerator的物件。(Enumerator實現了迭代器和列舉兩個介面) 300 private <T> Iterator<T> getIterator(int type) { 301 if (count == 0) { 302 return (Iterator<T>) emptyIterator; 303 } else { 304 return new Enumerator<T>(type, true); 305 } 306 } 307 308 // Hashtable的“key的集合”。它是一個Set,意味著沒有重複元素 309 private transient volatile Set<K> keySet = null; 310 // Hashtable的“key-value的集合”。它是一個Set,意味著沒有重複元素 311 private transient volatile Set<Map.Entry<K,V>> entrySet = null; 312 // Hashtable的“key-value的集合”。它是一個Collection,意味著可以有重複元素 313 private transient volatile Collection<V> values = null; 314 315 // 返回一個被synchronizedSet封裝後的KeySet物件 316 // synchronizedSet封裝的目的是對KeySet的所有方法都新增synchronized,實現多執行緒同步 317 public Set<K> keySet() { 318 if (keySet == null) 319 keySet = Collections.synchronizedSet(new KeySet(), this); 320 return keySet; 321 } 322 323 // Hashtable的Key的Set集合。 324 // KeySet繼承於AbstractSet,所以,KeySet中的元素沒有重複的。 325 private class KeySet extends AbstractSet<K> { 326 public Iterator<K> iterator() { 327 return getIterator(KEYS); 328 } 329 public int size() { 330 return count; 331 } 332 public boolean contains(Object o) { 333 return containsKey(o); 334 } 335 public boolean remove(Object o) { 336 return Hashtable.this.remove(o) != null; 337 } 338 public void clear() { 339 Hashtable.this.clear(); 340 } 341 } 342 343 // 返回一個被synchronizedSet封裝後的EntrySet物件 344 // synchronizedSet封裝的目的是對EntrySet的所有方法都新增synchronized,實現多執行緒同步 345 public Set<Map.Entry<K,V>> entrySet() { 346 if (entrySet==null) 347 entrySet = Collections.synchronizedSet(new EntrySet(), this); 348 return entrySet; 349 } 350 351 // Hashtable的Entry的Set集合。 352 // EntrySet繼承於AbstractSet,所以,EntrySet中的元素沒有重複的。 353 private class EntrySet extends AbstractSet<Map.Entry<K,V>> { 354 public Iterator<Map.Entry<K,V>> iterator() { 355 return getIterator(ENTRIES); 356 } 357 358 public boolean add(Map.Entry<K,V> o) { 359 return super.add(o); 360 } 361 362 // 查詢EntrySet中是否包含Object(0) 363 // 首先,在table中找到o對應的Entry(Entry是一個單向連結串列) 364 // 然後,查詢Entry連結串列中是否存在Object 365 public boolean contains(Object o) { 366 if (!(o instanceof Map.Entry)) 367 return false; 368 Map.Entry entry = (Map.Entry)o; 369 Object key = entry.getKey(); 370 Entry[] tab = table; 371 int hash = key.hashCode(); 372 int index = (hash & 0x7FFFFFFF) % tab.length; 373 374 for (Entry e = tab[index]; e != null; e = e.next) 375 if (e.hash==hash && e.equals(entry)) 376 return true; 377 return false; 378 } 379 380 // 刪除元素Object(0) 381 // 首先,在table中找到o對應的Entry(Entry是一個單向連結串列) 382 // 然後,刪除連結串列中的元素Object 383 public boolean remove(Object o) { 384 if (!(o instanceof Map.Entry)) 385 return false; 386 Map.Entry<K,V> entry = (Map.Entry<K,V>) o; 387 K key = entry.getKey(); 388 Entry[] tab = table; 389 int hash = key.hashCode(); 390 int index = (hash & 0x7FFFFFFF) % tab.length; 391 392 for (Entry<K,V> e = tab[index], prev = null; e != null; 393 prev = e, e = e.next) { 394 if (e.hash==hash && e.equals(entry)) { 395 modCount++; 396 if (prev != null) 397 prev.next = e.next; 398 else 399 tab[index] = e.next; 400 401 count--; 402 e.value = null; 403 return true; 404 } 405 } 406 return false; 407 } 408 409 public int size() { 410 return count; 411 } 412 413 public void clear() { 414 Hashtable.this.clear(); 415 } 416 } 417 418 // 返回一個被synchronizedCollection封裝後的ValueCollection物件 419 // synchronizedCollection封裝的目的是對ValueCollection的所有方法都新增synchronized,實現多執行緒同步 420 public Collection<V> values() { 421 if (values==null) 422 values = Collections.synchronizedCollection(new ValueCollection(), 423 this); 424 return values; 425 } 426 427 // Hashtable的value的Collection集合。 428 // ValueCollection繼承於AbstractCollection,所以,ValueCollection中的元素可以重複的。 429 private class ValueCollection extends AbstractCollection<V> { 430 public Iterator<V> iterator() { 431 return getIterator(VALUES); 432 } 433 public int size() { 434 return count; 435 } 436 public boolean contains(Object o) { 437 return containsValue(o); 438 } 439 public void clear() { 440 Hashtable.this.clear(); 441 } 442 } 443 444 // 重新equals()函式 445 // 若兩個Hashtable的所有key-value鍵值對都相等,則判斷它們兩個相等 446 public synchronized boolean equals(Object o) { 447 if (o == this) 448 return true; 449 450 if (!(o instanceof Map)) 451 return false; 452 Map<K,V> t = (Map<K,V>) o; 453 if (t.size() != size()) 454 return false; 455 456 try {