我理解WeakHashMap的概念,但字符串字面量和字符串对象使我难以理解。
以下是代码:
package com.lnt.StringBuf;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
public class Test1 {
public static void main(String[] args) {
Map w = new WeakHashMap();
Map h = new HashMap<>();
String hkey = new String("hashkey");
String wkey = new String("weakkey");
/* String hkey = "hashkey";
String wkey = "weakkey";*/
h.put(hkey, 1);
w.put(wkey, 1);
System.gc();
System.out.println("Before");
System.out.println("hashmap size: " + h.size());
System.out.println("weakmap size: " + w.size());
System.out.println("Hashmap value: " + h.get("hashkey") + "\t"
+ "weakmap value: " + w.get("weakkey"));
hkey = null;
wkey = null;
System.gc();
System.out.println(hkey+" "+wkey);
System.out.println("After");
System.out.println("hashmap size: " + h.size());
System.out.println("weakmap size: " + w.size());
System.out.println("Hashmap value: " + h.get("hashkey") + "\t"
+ "weakmap value: " + w.get("weakkey"));
System.out.println(h.entrySet());
System.out.println(w.entrySet());
}
}
输出结果为:
Before
hashmap size: 1
weakmap size: 1
Hashmap value: 1 weakmap value: 1
null null
After
hashmap size: 1
weakmap size: 0
Hashmap value: 1 weakmap value: null
[hashkey=1]
[]
但是当下面的代码替换掉原有代码后,输出结果会发生变化。
String hkey = "hashkey";
String wkey = "weakkey";
String hkey = "hashkey";
String wkey = "weakkey";
输出结果为:
Before
hashmap size: 1
weakmap size: 1
Hashmap value: 1 weakmap value: 1
null null
After
hashmap size: 1
weakmap size: 1
Hashmap value: 1 weakmap value: 1
[hashkey=1]
[weakkey=1]
问题:在WeakHashMap中,将字符串字面量和字符串对象设置为“null”会产生不同的影响。原因是什么?