最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Java編程WeakHashMap實(shí)例解析

 更新時(shí)間:2018年02月05日 13:45:07   作者:anialy  
這篇文章主要介紹了Java編程WeakHashMap實(shí)例解析,分享了相關(guān)代碼示例,小編覺(jué)得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下

簡(jiǎn)述:

Thinking in Java》第4版 P519 頁(yè) WeakHashMap一章讀書(shū)筆記

WeakHashMap 用來(lái)保存WeakReference,這一結(jié)構(gòu)云遜垃圾回收器自動(dòng)清理鍵和值

在添加鍵和值的操作時(shí),映射會(huì)自動(dòng)使用WeakReference包裝它們,

見(jiàn)jdk源代碼,

public V put(K key, V value) {
	Object k = maskNull(key);
	int h = hash(k);
	Entry<K,V>[] tab = getTable();
	int i = indexFor(h, tab.length);
	for (Entry<K,V> e = tab[i]; e != null; e = e.next) {
		if (h == e.hash && eq(k, e.get())) {
			V oldValue = e.value;
			if (value != oldValue) 
			        e.value = value;
			return oldValue;
		}
	}
	modCount++;
	Entry<K,V> e = tab[i];
	tab[i] = new Entry<>(k, value, queue, h, e);
	if (++size >= threshold) 
	    resize(tab.length * 2);
	return null;
}

其中new Entry<>(k, value, queue, h, e)一行使用了ReferenceQueue

/** 
 * Reference queue for cleared WeakEntries 
 */ 
private final ReferenceQueue<Object> queue = new ReferenceQueue<>(); 

點(diǎn)入new Entry的構(gòu)造函數(shù),進(jìn)入super頂層可以看到,

/** 
 * Creates a new weak reference that refers to the given object and is 
 * registered with the given queue. 
 * 
 * @param referent object the new weak reference will refer to 
 * @param q the queue with which the reference is to be registered, 
 *     or <tt>null</tt> if registration is not required 
 */ 
public WeakReference(T referent, ReferenceQueue<? super T> q) { 
  super(referent, q); 
} 

這里new Entry同時(shí)也構(gòu)造出來(lái)了一個(gè)WeakRefence對(duì)象

測(cè)試:

package com.anialy.test.data_structure.map;
import java.util.Iterator;
import java.util.WeakHashMap;
public class WeakHashMapTest {
	public static void main(String[] args) {
		WeakHashMap wmap = new WeakHashMap<String, Object>();
		final int SIZE = 10;
		String[] str = new String[SIZE];
		for (int i=0; i<SIZE; i++){
			String key = Integer.toString(i);
			String value = Integer.toString(i);
			// 每隔3個(gè)保留一個(gè)引用 
			if(i % 3 == 0) 
			        str[i] = key;
			wmap.put(key, value);
		}
		System.gc();
		Iterator iter = wmap.keySet().iterator();
		while(iter.hasNext()){
			System.out.println(wmap.get(iter.next()));
		}
	}
}

可以預(yù)料到,部分由于String[] 保留了弱引用,所以輸出都是間隔3的

總結(jié)

以上就是本文關(guān)于Java編程WeakHashMap實(shí)例解析的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!

相關(guān)文章

最新評(píng)論

偏关县| 农安县| 饶阳县| 安陆市| 镇雄县| 蓬溪县| 苍梧县| 罗定市| 谷城县| 白玉县| 安陆市| 稷山县| 大同市| 平塘县| 始兴县| 兰西县| 北宁市| 康马县| 阳东县| 海安县| 房山区| 平定县| 紫金县| 墨江| 绥阳县| 南平市| 陵川县| 长沙县| 五台县| 铅山县| 运城市| 上虞市| 民权县| 阿克陶县| 嘉峪关市| 缙云县| 阳谷县| 女性| 榆树市| 黑龙江省| 萍乡市|