复习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方法。看HashTable源码知道,其实它的contains方法就是containsValue。
新闻热点
疑难解答