Java WeakHashMap引用未更新

时间:2009-09-18 17:40:38

标签: java weak-references weakhashmap

在下面的代码中,我创建了一个Pen对象,并将其颜色初始化为白色。在Pen的构造函数中,在将字段'penColor'设置为传递给构造函数的值之后,我更新了一个全局静态弱hashmap,我将其保存在KEY是'this pointer - 在我的情况下是Pen,以及value是另一个weakhashmap,其KEY是字符串“penColor”,其值是对penColor成员字段的引用。

接下来,我的代码通过调用Pen的setColor函数来更新Pen的颜色。我本以为在这次更新之后,如果我在我的weakhashmap中查找Pen对象的颜色字段,它会反映新的颜色,但事实并非如此。有人可以解释为什么会这样吗?

package weakhashmaptest;


import java.awt.Color;
import java.util.WeakHashMap;
import java.util.Iterator;

public class Main {

    static WeakHashMap <Object, WeakHashMap>ownerMap = new WeakHashMap<Object, WeakHashMap>();

    public static void main(String[] args) {

        Pen r = new Pen(Color.WHITE);

        Iterator i = ownerMap.keySet().iterator();

        while(i.hasNext()) {
            Object key = i.next();
            System.out.println("\telement of hashmap is : " +ownerMap.get(key));
        }

        r.setColor(Color.BLACK);

        System.gc();

        i = ownerMap.keySet().iterator();

        while(i.hasNext()) {
            Object key = i.next();
            System.out.println("\telement of hashmap is : " +ownerMap.get(key));
        }

    }

    public static void mapUpdate(Object owner, Object reference, String field_name) {

        WeakHashMap reference_map = ownerMap.get(owner);

        if (reference_map == null) {         
            reference_map = new WeakHashMap();
            reference_map.put(field_name, reference);
        } else {         
            reference_map.put(field_name, reference);
        }

        ownerMap.put(owner, reference_map);

    }

}

class Pen {

    Color penColor;

    public Pen(Color c) {

        penColor = c;
        Main.mapUpdate(this, penColor, "penColor");

    }

    public void setColor(Color c) {

        penColor = c;

    }

}

1 个答案:

答案 0 :(得分:5)

您将 Color 对象的引用放入地图,而不是 Pen 。如果您将 Pen 放入地图,然后稍后询问笔的颜色,您会看到更改。

用非常简单的术语来说,你所做的与以下内容类似:

Pen pen = new Pen(Color.WHITE);
Color color = pen.penColor;
pen.setColor(Color.BLACK);
// color here still refers to Color.WHITE, not Color.BLACK.