日期:2014-05-20  浏览次数:20742 次

求救:关于WeakHashMap的困惑
package   statictest;
import   java.util.*;
class   A
{
int   a=3;
String   str= "hello ";

public   String   toString()  
{
return   str+String.valueOf(a);
}
}

public   class   StaticTest
{
public   static   void   main(String[]   args)   throws   Exception
{
        Map   map=new   WeakHashMap();        
        String   a= "a ";
        String   av= "av ";
        A   ca=new   A();
        map.put( "ca ",   ca);
        map.put(a,   av);      
        System.out.println(map);      
        System.gc();  
        a=null;
        ca=null;      
        Thread.sleep(1000);
        System.gc();        
        System.gc();          
        System.out.println(map);

        /*运行结果:
        {a=av,   ca=hello3}
        {a=av,   ca=hello3}
两次一样*/
       
        Map   map2=new   WeakHashMap();
        map2.put( "obj ",   new   A());
        A   xyz=(A)map2.get( "obj ");
        System.out.println(map2);
        xyz.a=10000;
        System.out.println(map2);
        /*运行结果:
                    {obj=hello3}
    {obj=hello10000}
        对象的成员变量可改变*/        
}

}

疑惑1:
为什么我把WeakHashMap的键设为了null,而且也调用了垃圾回收器,也让主线程休眠了一段时间,可是这个map还是不放掉这一对值?
疑惑2:
map里的值存的一律是引用,可是为什么我将第一个map的键ca对应的值设为了null,可是它打印出来还是原来的值?而第二个map2里面我更改了它里面保存对象的成员值后,能反应出正确的结果?


------解决方案--------------------
为什么会这样呢?lz运行的程序是不是有点问题?

import java.util.*;
class Mouse
{
private int i;
Mouse(int i){
this.i=i;
}
public String toString(){return "Mouse "+i;}
}
public class Test2
{
public static void main(String[] args)
{
Map hashMap=new WeakHashMap();
Mouse s=new Mouse(1);
s=null;
hashMap.put(s,new Integer(1));
//s=null;
System.out.println(hashMap);
}
}
java Test2
打印:null=1