|
As said upstairs, if the key is explicitly set to null, it can be added, if the key is an object, not a string, then when the object is null, weakhashmap will automatically reduce the capacity, put this key Value pairs are deleted from the collection.
The nature of the string is puzzling. Although it is the final class, the collection contains a reference, not its own. It is reasonable to say that this reference will point to the new object, but why still point to the old object? Shouldn't the old object be recycled by GC?
code show as below:
package statictest;
import java.util.*;
import java.lang.ref.*;
import java.lang.ref.*;
class A
{
int a=3;
String str="hello";
The
public String toString()
{
return str+a;
}
}
public class StaticTest
{
public static void main(String[] args) throws Exception
{
Map map=new WeakHashMap();
String b="this is b:";
A ab=new A();
map.put(ab, new A());
map.put(b, "b");
System.out.println(map);
String c=(String)map.get(b);
c=null; //Set the value of key b to null, but the printout has not changed.
ab=null; //Because ab is a reference to a class object, it will be moved out of the map
b=null; //But the key b is also an object, why does it not change when set to null? ?
System.gc(); //Must be called, otherwise GC will be too late to recycle, and the original key-value pair will still be printed out
System.out.println(map);
}
}
Print the result:
{hello3=hello3, this is b:=b}
{this is b:=b} |
|