Java 简明教程

Java WeakHashMap Class

Introduction

Java WeakHashMap 类是基于散列表的 Map 实现,其具有弱键。如果不再使用其键,则垃圾回收器将自动删除 WeakHashMap 中的条目。以下是有关 WeakHashMap 的重点 −

The Java WeakHashMap class is a hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed by the garbage collector, when its key is no longer in use. Following are the important points about WeakHashMap −

  1. Both null values and the null key are supported.

  2. Like most collection classes, this class is also not synchronized.

  3. This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.

  4. Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference.

  5. This class is a member of the Java Collections Framework.

Class declaration

以下是 java.util.WeakHashMap 类的声明 -

Following is the declaration for java.util.WeakHashMap class −

public class WeakHashMap<K,V>
   extends AbstractMap<K,V>
   implements Map<K,V>

此处 <K> 是此映射维护的键的类型,而 <V> 是映射值的类型。

Here <K> is the type of keys maintained by this map and <V> is the type of mapped values.

Class constructors

Class methods

Methods inherited

此类从以下类中继承方法:

This class inherits methods from the following classes −

  1. java.util.AbstractMap

  2. java.lang.Object

  3. java.util.Map

Adding a Key-Value Pair to a WeakHashMap of Integer, Integer Pairs Example

以下示例展示了在映射中放置少数值的 Java WeakHashMap put() 方法的用法。我们创建了一个整数、整数对的映射对象。接着使用 put() 方法添加了几条记录,然后打印映射。

The following example shows the usage of Java WeakHashMap put() method to put few values in a Map. We’ve created a Map object of Integer,Integer pairs. Then few entries are added using put() method and then map is printed.

package com.tutorialspoint;

import java.util.WeakHashMap;

public class WeakHashMapDemo {
   public static void main(String args[]) {

      // create hash map
      WeakHashMap<Integer,Integer> newmap = new WeakHashMap<>();

      // populate hash map
      newmap.put(1, 1);
      newmap.put(2, 2);
      newmap.put(3, 3);

      System.out.println("Map elements: " + newmap);
   }
}

Output

让我们编译并运行以上的程序,这会生成以下结果:

Let us compile and run the above program, this will produce the following result.

Map elements: {3=3, 2=2, 1=1}