e357. automatically removing an unreferenced element from a hash table.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 35 行

TXT
35
字号
When a key is added to a map, the map will prevent the key from being garbage-collected. However, a weak map will automatically remove a key if the key is not being referenced by any other object. An example where this type of map might be useful is a registry where a registrant is automatically removed after it is garbage-collected. 
    // Create the weak map
    Map weakMap = new WeakHashMap();
    
    // Add a key to the weak map
    weakMap.put(keyObject, valueObject);
    
    // Get all keys that are still being referenced
    Iterator it = weakMap.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
    }

The weak map does not automatically release the value if it is no longer used. To enable automatically release of the value, the value must be wrapped in a WeakReference object: 
    WeakReference weakValue = new WeakReference(valueObject);
    weakMap.put(keyObject, weakValue);
    
    // Get all keys that are still being referenced and check whether
    // or not the value has been garbage-collected
    it = weakMap.keySet().iterator();
    while (it.hasNext()) {
        // Get key
        Object key = it.next();
    
        weakValue = (WeakReference)weakMap.get(key);
        if (weakValue == null) {
            // Value has been garbage-collected
        } else {
            // Get value
            valueObject = weakValue.get();
        }
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?