在下面的代码示例中,将键设置为null并被System.gc()调用时,将WeakHashMap丢失所有映射并清空。
System.gc()
WeakHashMap
class WeakHashMapExample { public static void main(String[] args) { Key k1 = new Key("Hello"); Key k2 = new Key("World"); Key k3 = new Key("Java"); Key k4 = new Key("Programming"); Map<Key, String> wm = new WeakHashMap<Key, String>(); wm.put(k1, "Hello"); wm.put(k2, "World"); wm.put(k3, "Java"); wm.put(k4, "Programming"); k1=null; k2=null; k3=null; k4=null; System.gc(); System.out.println("Weak Hash Map :"+wm.toString()); } } class Key{ private String key; public Key(String key) { this.key=key; } @Override public boolean equals(Object obj) { return this.key.equals((String)obj); } @Override public int hashCode() { return key.hashCode(); } @Override public String toString() { return key; } }
Output: Weak Hash Map :{}
当WeakHashMap与HashMap和一起使用时,键设置为null,WeakHashMap则不会丢失其键值映射。
HashMap
class WeakHashMapExample { public static void main(String[] args) { Key k1 = new Key("Hello"); Key k2 = new Key("World"); Key k3 = new Key("Java"); Key k4 = new Key("Programming"); Map<Key, String> wm = new WeakHashMap<Key, String>(); Map<Key, String> hm=new HashMap<Key, String>(); wm.put(k1, "Hello"); wm.put(k2, "World"); wm.put(k3, "Java"); wm.put(k4, "Programming"); hm.put(k1, "Hello"); hm.put(k2, "World"); hm.put(k3, "Java"); hm.put(k4, "Programming"); k1=null; k2=null; k3=null; k4=null; System.gc(); System.out.println("Weak Hash Map :"+wm.toString()); System.out.println("Hash Map :"+hm.toString()); } } class Key{ private String key; public Key(String key) { this.key=key; } @Override public boolean equals(Object obj) { return this.key.equals((String)obj); } @Override public int hashCode() { return key.hashCode(); } @Override public String toString() { return key; } }
输出: Weak Hash Map :{Java=Java, Hello=Hello, World=World, Programming=Programming} Hash Map :{Programming=Programming, World=World, Java=Java, Hello=Hello}
Weak Hash Map :{Java=Java, Hello=Hello, World=World, Programming=Programming}
Hash Map :{Programming=Programming, World=World, Java=Java, Hello=Hello}
我的问题是,WeakHashMap即使丢弃了密钥,为什么在第二个代码示例中也不会丢失其条目?
一个WeakHashMap丢弃条目时,关键是不再活码强可到达。由于HashMap维护人员对键具有严格的引用,因此键仍然可以访问,WeakHashMap并且不会丢弃条目。
关键是行为与键对象的引用有关,而不是与一次引用键的任何变量的值有关。