1. 程式人生 > >【Java入門提高篇】Day34 Java容器類詳解(十五)WeakHashMap詳解

【Java入門提高篇】Day34 Java容器類詳解(十五)WeakHashMap詳解

public class WeakHashMapTest {
    public static void main(String[] args){
        testWeakHashMap();
    }

    private static void testWeakHashMap() {
        // 建立3個String物件用來做key
        String w1 = new String("key1");
        String w2 = new String("key2");
        String w3 = new String("key3");

        
// 新建WeakHashMap Map weakHashMap = new WeakHashMap(); // 新增鍵值對 weakHashMap.put(w1, "v1"); weakHashMap.put(w2, "v2"); weakHashMap.put(w3, "v3"); // 打印出weakHashMap System.out.printf("weakHashMap:%s\n", weakHashMap); // containsKey(Object key) :是否包含鍵key
System.out.printf("contains key key1 : %s\n",weakHashMap.containsKey("key1")); System.out.printf("contains key key4 : %s\n",weakHashMap.containsKey("key4")); // containsValue(Object value) :是否包含值value System.out.printf("contains value v1 : %s\n",weakHashMap.containsValue("v1")); System.out.printf(
"contains value 0 : %s\n",weakHashMap.containsValue(0)); // remove(Object key) : 刪除鍵key對應的鍵值對 weakHashMap.remove("three"); System.out.printf("weakHashMap: %s\n", weakHashMap); // ---- 測試 WeakHashMap 的自動回收特性 ---- // 將w1設定null。 // 這意味著“弱鍵”w1再沒有被其它物件引用,呼叫gc時會回收WeakHashMap中與“w1”對應的鍵值對 w1 = null; // 記憶體回收。這裡,會回收WeakHashMap中與“w1”對應的鍵值對 System.gc(); // 遍歷WeakHashMap Iterator iter = weakHashMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry en = (Map.Entry)iter.next(); System.out.printf("next : %s - %s\n",en.getKey(),en.getValue()); } // 列印WeakHashMap的實際大小 System.out.printf("after gc WeakHashMap size:%s\n", weakHashMap.size()); } }