📜  Java中的WeakHashMap类

📅  最后修改于: 2022-05-13 01:55:18.663000             🧑  作者: Mango

Java中的WeakHashMap类

WeakHashMap 是 Map 接口的一个实现。 WeakHashMap 与 HashMap 几乎相同,但在 WeakHashMap 的情况下,如果对象被指定为键不包含任何引用 - 即使它与 WeakHashMap 相关联,它也有资格进行垃圾回收。即垃圾收集器在 WeakHashMap 上占主导地位。

WeakHashMap 是 Map 接口的基于哈希表的实现,带有弱键。 WeakHashMap 中的条目在其键不再常用时将被自动删除。更准确地说,给定键的映射的存在不会阻止该键被垃圾收集器丢弃,也就是说,使其可终结,最终确定,然后回收。当一个键被丢弃时,它的条目被有效地从映射中删除,所以这个类的行为与其他映射实现有些不同。

WeakHashMap 类的几个重要特性是:

  • WeakHashMap 支持空值和空键。
  • 它不同步。
  • 此类主要用于关键对象,其 equals 方法使用 ==运算符测试对象身份。

WeakHashMap 中的构造函数

1. WeakHashMap():这个构造函数用于创建一个空的WeakHashMap,默认初始容量-(16),加载因子(0.75)。

2. WeakHashMap(int initialCapacity):该构造函数用于创建一个空的WeakHashMap,具有给定的初始容量和默认的加载因子(0.75)。

3. WeakHashMap(int initialCapacity, float loadFactor):该构造函数用于创建一个具有给定初始容量和给定负载因子的空WeakHashMap。

4. WeakHashMap(Map m):该构造函数用于创建一个新的WeakHashMap,其映射与指定的映射相同。

WeakHashMap 中的方法

MethodAction Performed
clear()Removes all of the mappings from this map. The map will be empty after this call returns. 
containsValue(Object value)Returns true if this map maps one or more keys to the specified value. 
containsKey(Object key)Returns true if this map contains a mapping for the specified key. 
entrySet()Returns a Set view of the mappings contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
get(Object key)Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 
isEmpty()Returns true if this map contains no key-value mappings. This result is a snapshot, and may not reflect unprocessed entries that will be removed before next attempted access because they are no longer referenced.
keySet()Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.
put(K key, V value)Associates the specified value with the specified key in this map. If the map previously contained a mapping for this key, the old value is replaced.
putAll(Map m)Copies all of the mappings from the specified map to this map. These mappings will replace any mappings that this map had for any of the keys currently in the specified map.
remove(Object key)Removes the mapping for a key from this weak hash map if it is present. More formally, if this map contains a mapping from key k to value v such that (key==null ? k==null: key.equals(k)), that mapping is removed.
size()Returns the number of key-value mappings in this map. This result is a snapshot, and may not reflect unprocessed entries that will be removed before the next attempted access because they are no longer referenced. 
values()Returns a Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator’s own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

示例 1:

Java
// Java Program to Illustrate WeakHashMap class
// Via close(), containsValue(), containsKey()
// and isEmpty() method
  
// Importing required classes
import java.util.Map;
import java.util.WeakHashMap;
  
// Main class
// WeakHashMapdemo
class GFG {
  
    // Main driver method
    public static void main(String[] arg)
    {
  
        // Creating an empty WeakHashMap
        // of Number and string type
        Map weak
            = new WeakHashMap();
  
        // Inserting custom elements
        // using put() method
        weak.put(1, "geeks");
        weak.put(2, "for");
        weak.put(3, "geeks");
  
        // Printing and alongside checking weak map
        System.out.println("our weak map: " + weak);
  
        // Checking if "for" exist
        if (weak.containsValue("for"))
            System.out.println("for exist");
  
        // Checking if 1 exist as a key in Map
        if (weak.containsKey(1))
            System.out.println("1 exist");
  
        // Removing all data
        // using clear() method
        weak.clear();
  
        // Checking whether the Map is empty or not
        // using isEmpty() method
        if (weak.isEmpty())
  
            // Display message for better readability
            System.out.println("empty map: " + weak);
    }
}


Java
// Java Program to Illustrate WeakHashMap class
// Via entrySet(), keySet() and Values() Method
  
// Importing required classes
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
  
// Main class
// WeakHashMapdemo
class GFG {
  
    // Main driver method
    public static void main(String[] arg)
    {
  
        // Creating an empty WeakHashMap
        // of number and string type
        Map weak
            = new WeakHashMap();
  
        // Inserting elements
        // using put() method
        weak.put(1, "geeks");
        weak.put(2, "for");
        weak.put(3, "geeks");
  
        // Creating object of Set interface
        Set set1 = weak.entrySet();
  
        // Checking above Set
        System.out.println(set1);
  
        // Creating set for key
        Set keySet = weak.keySet();
  
        // Checking keySet
        System.out.println("key set: " + keySet);
  
        Collection value = weak.values();
  
        // Checking values of map and printing them
        System.out.println("values: " + value);
    }
}


Java
// Java code remove(), putAll()
// get() and size() method
  
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
  
class WeakHashMapdemo {
    public static void main(String[] arg)
    {
        Map weak
            = new WeakHashMap();
        weak.put(1, "geeks");
        weak.put(2, "for");
        weak.put(3, "geeks");
  
        Map weak1
            = new WeakHashMap();
        weak1.putAll(weak);
  
        // Getting value of key 2
        System.out.println(weak1.get(2));
  
        // Printing the size of map
        // using size() method
        System.out.println("Size of map is: "
                           + weak1.size());
  
        // Removing second element
        // using standard remove() method
        weak1.remove(2);
  
        // Printing the size after removing key and value
        // pair
        System.out.println("Size after removing: "
                           + weak1.size());
    }
}


输出
our weak map: {3=geeks, 2=for, 1=geeks}
for exist
1 exist
empty map: {}

示例 2:

Java

// Java Program to Illustrate WeakHashMap class
// Via entrySet(), keySet() and Values() Method
  
// Importing required classes
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
  
// Main class
// WeakHashMapdemo
class GFG {
  
    // Main driver method
    public static void main(String[] arg)
    {
  
        // Creating an empty WeakHashMap
        // of number and string type
        Map weak
            = new WeakHashMap();
  
        // Inserting elements
        // using put() method
        weak.put(1, "geeks");
        weak.put(2, "for");
        weak.put(3, "geeks");
  
        // Creating object of Set interface
        Set set1 = weak.entrySet();
  
        // Checking above Set
        System.out.println(set1);
  
        // Creating set for key
        Set keySet = weak.keySet();
  
        // Checking keySet
        System.out.println("key set: " + keySet);
  
        Collection value = weak.values();
  
        // Checking values of map and printing them
        System.out.println("values: " + value);
    }
}
输出
[3=geeks, 2=for, 1=geeks]
key set: [3, 2, 1]
values: [geeks, for, geeks]

示例 3:

Java

// Java code remove(), putAll()
// get() and size() method
  
import java.util.Collection;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
  
class WeakHashMapdemo {
    public static void main(String[] arg)
    {
        Map weak
            = new WeakHashMap();
        weak.put(1, "geeks");
        weak.put(2, "for");
        weak.put(3, "geeks");
  
        Map weak1
            = new WeakHashMap();
        weak1.putAll(weak);
  
        // Getting value of key 2
        System.out.println(weak1.get(2));
  
        // Printing the size of map
        // using size() method
        System.out.println("Size of map is: "
                           + weak1.size());
  
        // Removing second element
        // using standard remove() method
        weak1.remove(2);
  
        // Printing the size after removing key and value
        // pair
        System.out.println("Size after removing: "
                           + weak1.size());
    }
}
输出
for
Size of map is: 3
Size after removing: 2