0

在下面的示例中,如果垃圾收集器用作weakHashMap 中的键,则垃圾收集器正在销毁一个无用(引用较少)的对象,这没关系.. 但是如果有任何无用的对象作为值,那么垃圾收集器为什么不销毁该对象..

     public class WeakHashMapDemo {
    public static void main(String[] args) throws InterruptedException{
        WeakHashMap whs=new WeakHashMap();
        Temp t=new Temp();
        Temp t1=new Temp();
        Integer x=new Integer(5);
        Integer y=6;
        whs.put(t,"hemant");
        whs.put("hemant", t1);
        whs.put(x,"durga");
        whs.put(y,"bacon");
        System.out.println(whs);
        t=null;
        t1=null;
        x=null;
        y=null;
        System.gc();
        Thread.sleep(2000);
        System.out.println(whs);
    }
}   

临时等级:-

class Temp{

    @Override
    public String toString() {
        return "temp"; //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    protected void finalize() throws Throwable {
        System.out.println("finalize() mrthod is called");

    }



}  

输出

  {hemant=temp, 6=bacon, 5=durga, temp=hemant}
  finalize() mrthod is called
  {hemant=temp, 6=bacon}  

根据我的输出应该是: -

  {hemant=temp, 6=bacon, 5=durga, temp=hemant}
  finalize() mrthod is called
  {hemant=null}  
4

1 回答 1

0

WeakHashMap被定义为具有弱键但不具有弱值:

Map 接口的基于哈希表的实现,带有弱键。WeakHashMap 中的条目在其键不再常用时将被自动删除。

如果对键有任何引用,则键和值对将继续存在于映射中。

"Hemant"仍然存在,因为它是一个字符串文字,所以在字符串池中,并且6将存在,因为它是一个小的整数文字,所以它在整数池中。

分配给且不存在的对象xt因为它们是使用new创建新对象的关键字创建的,然后将它们设置为 null,从而删除对该对象的唯一引用。

所以因为仍然有引用"Hemant"6然后这些键和它们的值将保留在映射中。

于 2016-05-05T15:54:25.803 回答