java 弱哈希映射示例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10599710/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WeakHashMap example
提问by Anand
I create a WeakHashMap as
我创建了一个 WeakHashMap 作为
WeakHashMap<Employee,String> map = new WeakHashMap<Employee,String>();
map.put(emp,"hello");
where emp is an Employee object. Now if I do emp = null or say emp object is no longer referenced, then will the entry be removed from the WeakHashMap i.e. will the size of Map be zero?
And will it be vice-versa in case of HashMap?
Is my understanding of WeakHashMap correct?
其中 emp 是一个 Employee 对象。现在如果我做 emp = null 或者说 emp 对象不再被引用,那么条目是否会从 WeakHashMap 中删除,即 Map 的大小是否为零?
在 HashMap 的情况下,反之亦然吗?
我对 WeakHashMap 的理解正确吗?
采纳答案by Anand
I ran the sample code to understand the difference between HashMap
and WeakHashMap
我运行了示例代码以了解HashMap
和WeakHashMap
Map hashMap= new HashMap();
Map weakHashMap = new WeakHashMap();
String keyHashMap = new String("keyHashMap");
String keyWeakHashMap = new String("keyWeakHashMap");
hashMap.put(keyHashMap, "helloHash");
weakHashMap.put(keyWeakHashMap, "helloWeakHash");
System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
keyHashMap = null;
keyWeakHashMap = null;
System.gc();
System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
The output will be:
输出将是:
Before: hash map value:helloHash and weak hash map value:helloWeakHash
After: hash map value:helloHash and weak hash map value:null
回答by Yanflea
A very simple example, to enlighten what has already been said :
一个非常简单的例子,以启发已经说过的内容:
import java.util.WeakHashMap;
public class WeakHashMapDemo {
public static void main(String[] args) {
// -- Fill a weak hash map with one entry
WeakHashMap<Data, String> map = new WeakHashMap<Data, String>();
Data someDataObject = new Data("foo");
map.put(someDataObject, someDataObject.value);
System.out.println("map contains someDataObject ? " + map.containsKey(someDataObject));
// -- now make someDataObject elligible for garbage collection...
someDataObject = null;
for (int i = 0; i < 10000; i++) {
if (map.size() != 0) {
System.out.println("At iteration " + i + " the map still holds the reference on someDataObject");
} else {
System.out.println("somDataObject has finally been garbage collected at iteration " + i + ", hence the map is now empty");
break;
}
}
}
static class Data {
String value;
Data(String value) {
this.value = value;
}
}
}
Output :
输出 :
map contains someDataObject ? true
...
At iteration 6216 the map still holds the reference on someDataObject
At iteration 6217 the map still holds the reference on someDataObject
At iteration 6218 the map still holds the reference on someDataObject
somDataObject has finally been garbage collected at iteration 6219, hence the map is now empty
回答by aioobe
*will the entry be removed from the WeakHashMap i.e. will the size of Map be zero? *
*该条目是否会从 WeakHashMap 中删除,即 Map 的大小是否为零?*
If emp
contained the last reference making the Employee strongly reachablethen the entry in the map maybe removed.
如果emp
包含使 Employee强可达的最后一个引用,则地图中的条目可能会被删除。
The Java docs sums it up pretty well:
Java 文档总结得很好:
A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector [...]. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.
具有弱键的基于哈希表的 Map 实现。WeakHashMap 中的条目在其键不再正常使用时将自动删除。更准确地说,给定键的映射的存在不会阻止该键被垃圾收集器丢弃 [...]。当一个键被丢弃时,它的条目被有效地从映射中删除,所以这个类的行为与其他映射实现有些不同。
And will it be vice-versa in case of HashMap?
在 HashMap 的情况下,反之亦然吗?
Removing the entry from the WeakHashMap will not affect any other references in the program.
从 WeakHashMap 中删除条目不会影响程序中的任何其他引用。
回答by Premraj
WeakHashMap example:
WeakHashMap 示例:
Map map = new WeakHashMap();
Foo foo = new Foo();
map.put(foo, "bar");
foo=null; // strong refrence is removed and object is available for garbage collection.
HashMap example:
哈希映射示例:
Map map = new HashMap();
Foo foo = new Foo();
map.put(foo, "bar");
foo=null; // even though the reference is nullified object will not garbage collected because map is having Strong refrence.
回答by Kumar Bhatia
Reference in java are memory address where the created objects points in the memory. In a WeakHashMap, concept of Weak Reference is used.
java中的引用是创建的对象在内存中指向的内存地址。在 WeakHashMap 中,使用了弱引用的概念。
As soon as you create an object in java and assign it to some variable, it becomes strongly reachable.
一旦您在 java 中创建一个对象并将其分配给某个变量,它就会变得强可达。
Weak reference object can somewhat be similar to object that has no memory references i.e. it can be garbage collected now.
弱引用对象在某种程度上类似于没有内存引用的对象,即它现在可以被垃圾收集。
回答by Deepa Bhatia
In other Map implementations like a HashMap, the keys are strongly reachable. For example, if a HashMap has keys as Person class as shown below and if Person object is set to null, even after this if we will do map.get(Person) we will get the value from the memory since the keys are strongly referenced in a HashMap.
在其他 Map 实现(如 HashMap)中,键是强可达的。例如,如果 HashMap 具有如下所示的 Person 类的键,并且如果 Person 对象设置为 null,即使在此之后,如果我们执行 map.get(Person) 我们将从内存中获取值,因为键是强引用的在 HashMap 中。
wm.put(person, person.getFirstName());
person = null;
System.gc();
System.out.println("Hash Map :" + wm.toString());
Output : Hash Map :{test.Person@12dacd1=John}
输出:哈希映射:{test.Person@12dacd1=John}
Compared to HashMap, WeakHashMap is the one which will remove its enteries as soon as the keys have no reference in the memory. For example, if a WeakHashMap has keys as Person class as shown below and if Person object is set to null, now if you do map.get(Person) we will get null out of it because the key has no reference (or rather weakly reachable).
与 HashMap 相比,WeakHashMap 是一种一旦键在内存中没有引用就会删除其条目的方法。例如,如果 WeakHashMap 具有如下所示的 Person 类的键,并且如果 Person 对象设置为 null,那么现在如果你执行 map.get(Person) 我们将得到 null 因为键没有引用(或者说弱可达)。
wm.put(person, person.getFirstName());
person = null;
System.gc();
System.out.println("Weak Hash Map :" + wm.toString());
Output : Weak Hash Map :{}
输出:弱哈希映射:{}