Java 中的WeakHashMap实现了Map接口,并表示一个具有弱键的哈希表。 如果按键不是通常使用的,则将从地图中自动删除该条目。 这就是它与其他Map实现的区别。

支持空值和非空值,并且在初始容量和负载因子方面,其性能类似于HashMap类。
默认情况下,此类不同步。
HashMap和WeakHashMap之间的主要区别:

WeakHashMap实现Map并扩展AbstractMap。
WeakHashMap中的构造方法
WeakHashMap():创建一个空的WeakHashMap,默认初始容量为 16,负载系数为 0.75。WeakHashMap(int initialCapacity):创建具有指定容量的空WeakHashMap。WeakHashMap(int initialCapacity, float loadFactor):创建具有指定容量和负载因子的空WeakHashMap。WeakHashMap(Map<? extends K, ? extends V> m):创建一个具有与指定映射相同的映射的新WeakHashMap。
WeakHashMap中的方法
void clear():从当前映射中删除所有映射。boolean containsKey(Object key):如果当前映射包含指定键的映射,则返回true。boolean containsValue(Object value):如果当前映射中有映射到指定值的一个或多个键,则返回true。V get(Object key):返回指定键所映射到的值;如果该映射不包含指定键的映射,则返回null。boolean isEmpty():如果映射为空,则返回true,否则返回false。V put(K key, V value):将指定值“放入”当前映射中的指定键。V remove(Object key):如果存在,则从此WeakHashMap中删除键的映射。int size():返回映射中的映射数。
有关所有方法的文档,请访问 Oracle 官方文档页面。
一个执行上述某些方法的示例程序:
// importing the necessary library which is under java.util.*import java.util.*;public class WeakHashMapExample{public static void main(String args[])throws Exception{// declaration of an instance of WeakHashMap that takes a number as a key and string as a valueMap<Number, String> animals = new WeakHashMap<Number, String>();// populating the mapanimals.put(1, "Elephant");animals.put(2, "Tiger");animals.put(3, "Lion");// condition that checks for a certain valueif(animals.containsValue("Tiger"))System.out.println("Tiger exists.");// condition that checks for a certain keyif(animals.containsKey(3))System.out.println("'3' key exists.");// removing a specific keyanimals.remove(1);System.out.println(animals);// deletes all mappingsanimals.clear();// check if weakhashmap is emptyif(animals.isEmpty())System.out.println(animals);}}
输出:
Tiger exists.'3' key exists.{3=Lion, 2=Tiger}{}
