欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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());
}
}