WeakHashMap<String, String> weakHashMap = new WeakHashMap<>();
weakHashMap.put(new String("qwe"), "qwe");
System.out.println(weakHashMap.get("qwe"));
System.gc();
System.out.println(weakHashMap.get("qwe"));
WeakHashMap<String, String> weakHashMap = new WeakHashMap<>();
weakHashMap.put("qwe", "qwe");
System.out.println(weakHashMap.get("qwe"));
System.gc();
System.out.println(weakHashMap.get("qwe"));
WeakHashMap如果遇到key没有在被引用的时候,当gc触发的时候当前的key和value会被回收。但是前提是你的key是弱引用而不是强引用。当key变成强引用以后,gc无法释放。那么key就一直存在,当使用WeakHashMap用作缓存的时候,有可能内存溢出。