復習java基礎,隨便做個筆記。
1、HashMap和HashTable都是一直鍵值對應的數據結構。
2、它們繼承的父類不一樣:
public class HashMap<K, V> extends AbstractMap<K, V> implements Map<K, V>, Cloneable, Serializable
public class Hashtable<K, V> extends Dictionary<K, V> implements Map<K, V>, Cloneable, Serializable
3、HashMap是非線性安全的,HashTable是線性安全的:
HashMap源碼的put方法:
public V put(K paramK, V paramV)
HashTable源碼的put方法:
public synchronized V put(K paramK, V paramV)
4、HashMap運行key或value為null,HashTable不允許:
HashMap源碼:
public V put(K paramK, V paramV) { if (this.table == EMPTY_TABLE) inflateTable(this.threshold); if (paramK == null) return putForNullKey(paramV); int i = hash(paramK); int j = indexFor(i, this.table.length); for (Entry localEntry = this.table[j]; localEntry != null; localEntry = localEntry.next) { Object localObject1; if ((localEntry.hash != i) || (((localObject1 = localEntry.key) != paramK) && (!(paramK.equals(localObject1))))) continue; Object localObject2 = localEntry.value; localEntry.value = paramV; localEntry.recordaccess(this); return localObject2; } this.modCount += 1; addEntry(i, paramK, paramV, j); return null; }
HashTable源碼:
public synchronized V put(K paramK, V paramV) { if (paramV == null) throw new NullPointerException(); Entry[] arrayOfEntry = this.table; int i = hash(paramK); int j = (i & 0x7FFFFFFF) % arrayOfEntry.length; for (Entry localEntry = arrayOfEntry[j]; localEntry != null; localEntry = localEntry.next) { if ((localEntry.hash != i) || (!(localEntry.key.equals(paramK)))) continue; Object localObject = localEntry.value; localEntry.value = paramV; return localObject; } this.modCount += 1; if (this.count >= this.threshold) { rehash(); arrayOfEntry = this.table; i = hash(paramK); j = (i & 0x7FFFFFFF) % arrayOfEntry.length; } localEntry = arrayOfEntry[j]; arrayOfEntry[j] = new Entry(i, paramK, paramV, localEntry); this.count += 1; return null; }
5、HashTable有contains方法,HashMap沒有contains方法??碒ashTable源碼知道,其實它的contains方法就是containsValue。
新聞熱點
疑難解答