WeakHashMap String键值探究
程序员文章站
2022-05-09 19:56:51
...
今天研究了一下WeakHashMap 出现了一个现象,使用String key1="key1" 与String key1=new String("key1") 结果大不相同,代码如下,还请大家帮忙分析一下:
import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; public class TestWeakHashMap { public static void main(String[] args) throws InterruptedException { String key1 = new String("k1"); String key2 = new String("K2"); //String key1 = "k1"; //String key2 = "k2"; Map<String,String> map = new HashMap<String,String>(); Map<String,String> wmap = new WeakHashMap<String,String>(); map.put(key1, "val1"); map.put(key2, "val2"); wmap.put(key1, "wval1"); wmap.put(key2, "wval2"); map.remove(key2); key2 = null; key1 = null; System.gc(); System.out.println("first access: " + wmap.size()); System.out.println("second access: " + wmap.size()); System.out.println("map: " + map.toString()); System.out.println("wmap: " + wmap.toString()); } }