Confuse about java.util.WeakHashMap behavior?

41 Views Asked by At

Here is three cases, Why case1 result is {name=Bob}, however case2 result is {}, case3 is still {name=Bob}. the different between case1 and case2 is putting different key. run at JDK8. Why?

    //Case1:
    WeakHashMap<String,String> mapCase1 = new WeakHashMap<>();
    mapCase1.put("name", "Bob");
    System.gc();
    Thread.sleep(3000);
    System.out.println(mapCase1); //{name=Bob}
    //Case2:
    WeakHashMap<String,String> mapCase2 = new WeakHashMap<>();
    mapCase2.put(new String("name"), "Bob");
    System.gc();
    Thread.sleep(3000);
    System.out.println(mapCase2); //{}
    //Case3:
    WeakHashMap<String,String> mapCase3 = new WeakHashMap<>();
    String map3Key = new String("name");
    mapCase3.put(map3Key, "Bob");
    System.gc();
    Thread.sleep(3000);
    System.out.println(mapCase3); //{name=Bob}
0

There are 0 best solutions below