我正在理解 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 = new String("hashkey"); 字符串 wkey = new String("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 中以不同的方式使字符串字面量和字符串对象“空”产生影响。是什么原因?