Hashtable学习笔记
生活随笔
收集整理的這篇文章主要介紹了
Hashtable学习笔记
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Hashtable常用特點區(qū)分: ? ?1、extends Dictionary ;2、線程安全;3、key和value!=null;4、默認容量11;負載因子0.75;5、容量擴展old<<2+1./***源碼淺析*///繼承Dictionary實現(xiàn)Map, Cloneable, java.io.Serializablepublic class Hashtable<K,V>extends Dictionary<K,V>implements Map<K,V>, Cloneable, java.io.Serializable//4個構(gòu)造,同HashMap一樣//第一個構(gòu)造傳入容量和負載因子public Hashtable(int initialCapacity, float loadFactor) {//傳入容量不能小于0,if (initialCapacity < 0)throw new IllegalArgumentException("Illegal Capacity: "+initialCapacity);? //負載因子不能小于等于0或者是非數(shù)if (loadFactor <= 0 || Float.isNaN(loadFactor))throw new IllegalArgumentException("Illegal Load: "+loadFactor);//如果容量為0,則置為1,容量最小就是1if (initialCapacity==0)initialCapacity = 1;this.loadFactor = loadFactor;//table是以容量大小為初始大小的數(shù)組table = new Entry[initialCapacity];?//臨界值計算=容量乘以負載因子和當前系統(tǒng)數(shù)組最大長度加1的最小值,當達到臨界值就需要擴容threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);initHashSeedAsNeeded(initialCapacity);}// 添加初始的容量,負載因子默認0.75public Hashtable(int initialCapacity) {this(initialCapacity, 0.75f);}// 容器默認11,負載因子默認0.75public Hashtable() {this(11, 0.75f);}// 初始容器取map最大尺寸*2和11取大的,也就是最小也是11,負載因子0.75public Hashtable(Map<? extends K, ? extends V> t) {this(Math.max(2*t.size(), 11), 0.75f);//調(diào)用putAll將map中的數(shù)據(jù)加入hashtable中putAll(t);}//Hashtable大部分方法屬性都是加了同步鎖,所以Hashtable是線程安全的//返回所有key枚舉對象public synchronized Enumeration<K> keys() {return this.<K>getEnumeration(KEYS);}//返回所有value枚舉對象public synchronized Enumeration<V> elements() {return this.<V>getEnumeration(VALUES);}//判斷Hashtable的值是否等于valuepublic synchronized boolean contains(Object value) {//value不能等于nullif (value == null) {throw new NullPointerException();} //遍歷數(shù)組查找數(shù)組元素是否與value相等Entry tab[] = table;for (int i = tab.length ; i-- > 0 ;) {for (Entry<K,V> e = tab[i] ; e != null ; e = e.next) {if (e.value.equals(value)) {return true;}}}return false;}//判斷Hashtable是否包含傳入keypublic synchronized boolean containsKey(Object key) {Entry tab[] = table; //獲取key的hash值int hash = hash(key); //計算在數(shù)組的索引int index = (hash & 0x7FFFFFFF) % tab.length;? ? ? ? //找到key對應的鏈表,找出hash值和key值都相等的元素for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {if ((e.hash == hash) && e.key.equals(key)) {return true;}}return false;}?//返回key對應的value,沒有值得話返回nullpublic synchronized V get(Object key) {Entry tab[] = table;? ? ? ? //計算key對應的hash值int hash = hash(key);? ? ? ? //根據(jù)hash計算對應的索引int index = (hash & 0x7FFFFFFF) % tab.length;? ? ? ? //根據(jù)索引找到對應的鏈表,在鏈表中查找hash值和key值都相等的元素for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {if ((e.hash == hash) && e.key.equals(key)) {return e.value;}}return null;}//調(diào)整Hashtable的長度,使其達到(oldCapacity << 1) + 1protected void rehash() {int oldCapacity = table.length;Entry<K,V>[] oldMap = table;// overflow-conscious codeint newCapacity = (oldCapacity << 1) + 1;if (newCapacity - MAX_ARRAY_SIZE > 0) {if (oldCapacity == MAX_ARRAY_SIZE)// Keep running with MAX_ARRAY_SIZE bucketsreturn;newCapacity = MAX_ARRAY_SIZE;}Entry<K,V>[] newMap = new Entry[newCapacity];modCount++;? ? ? ? //臨界值=新容量*負載因子和數(shù)組元素實際容量加1的minthreshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);boolean rehash = initHashSeedAsNeeded(newCapacity);table = newMap;? ? ? ? //將原有元素復制到新的Hashtable中for (int i = oldCapacity ; i-- > 0 ;) {for (Entry<K,V> old = oldMap[i] ; old != null ; ) {Entry<K,V> e = old;old = old.next;if (rehash) {e.hash = hash(e.key);}? ? ? ? ? ? ? ? //計算新索引int index = (e.hash & 0x7FFFFFFF) % newCapacity;e.next = newMap[index];newMap[index] = e;}}}//添加鍵值對public synchronized V put(K key, V value) {? ? ? ? // value不等于nullif (value == null) {throw new NullPointerException();}? ? ? ? //若添加的key在Hashtable已經(jīng)存在,則用新value覆蓋原有的valueEntry tab[] = table;int hash = hash(key);int index = (hash & 0x7FFFFFFF) % tab.length;for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {if ((e.hash == hash) && e.key.equals(key)) {V old = e.value;e.value = value;return old;}}? ? ? ? //若不存在鍵值等于key的鍵值對,+1modCount++;? ? ? ? //如果Hashtable實際容量大于臨界值,擴容if (count >= threshold) {// Rehash the table if the threshold is exceededrehash();tab = table;hash = hash(key);index = (hash & 0x7FFFFFFF) % tab.length;}// Creates the new entry.? ? ? ? //將新的鍵值對插入對應數(shù)組索引為index的位置所在鏈表的表頭.Entry<K,V> e = tab[index];tab[index] = new Entry<>(hash, key, value, e);count++;return null;}?//刪除鍵值為key的鍵值對public synchronized V remove(Object key) {Entry tab[] = table;int hash = hash(key);? ? ? ? //計算索引int index = (hash & 0x7FFFFFFF) % tab.length;? ? ? ? //因為是單鏈表,所以刪除的時候要保留要刪除節(jié)點的前一個節(jié)點for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {if ((e.hash == hash) && e.key.equals(key)) {modCount++;if (prev != null) {prev.next = e.next;} else {tab[index] = e.next;}count--;V oldValue = e.value;e.value = null;return oldValue;}}return null;}//多次調(diào)用put方法添加數(shù)據(jù)public synchronized void putAll(Map<? extends K, ? extends V> t) {for (Map.Entry<? extends K, ? extends V> e : t.entrySet())put(e.getKey(), e.getValue());}//通過遍歷數(shù)組的方式將數(shù)組元素key值置為null,value不理會public synchronized void clear() {Entry tab[] = table;modCount++;for (int index = tab.length; --index >= 0; )tab[index] = null;count = 0;}//克隆Hashtablepublic synchronized Object clone() {try {? ? ? ? ? ? //克隆一個相同的空HashtableHashtable<K,V> t = (Hashtable<K,V>) super.clone();t.table = new Entry[table.length];? ? ? ? ? ? //將原有元素一次克隆到相應位置for (int i = table.length ; i-- > 0 ; ) {t.table[i] = (table[i] != null)? (Entry<K,V>) table[i].clone() : null;}? ? ? ? ? ? //將延伸變量置空t.keySet = null;t.entrySet = null;t.values = null;t.modCount = 0;return t;} catch (CloneNotSupportedException e) {// this shouldn't happen, since we are Cloneablethrow new InternalError();}}//重寫toString,遍歷元素,生成{"key" = "value"},當長度達到最大值,結(jié)束public synchronized String toString() {int max = size() - 1;if (max == -1)return "{}";StringBuilder sb = new StringBuilder();Iterator<Map.Entry<K,V>> it = entrySet().iterator();sb.append('{');for (int i = 0; ; i++) {Map.Entry<K,V> e = it.next();K key = e.getKey();V value = e.getValue();sb.append(key? ?== this ? "(this Map)" : key.toString());sb.append('=');sb.append(value == this ? "(this Map)" : value.toString());if (i == max)return sb.append('}').toString();sb.append(", ");}}
總結(jié)
以上是生活随笔為你收集整理的Hashtable学习笔记的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hash表学习笔记
- 下一篇: Linux常用指令收集