Java.util.WeakHashMap 类

java.util.WeakHashMap.keySet() 方法返回WeakHashMap中包含的键的 Set 视图。该集合由map支持,因此对map的更改会反映在集合中,反之亦然。

语法

public Set<K> keySet() 

参数

无参数。

返回值

返回此WeakHashMap中包含的键的集合视图。

异常

示例:

在下面的示例中,java.util.WeakHashMap.keySet() 方法返回给定 WeakHashMap 中包含的键。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建weakhashmap
    WeakHashMap<Integer, String> MyMap = new WeakHashMap<Integer, String>();

    //填充map
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");
    MyMap.put(104, "Jo");
    MyMap.put(105, "Sam");

    //打印map内容
    System.out.println("MyMap contains: " + MyMap);

    //创建map键的集合视图
    Set SetView = MyMap.keySet();

    //打印按键设置视图
    System.out.println("SetView contains: " + SetView);
  }
} 

上述代码的输出将是:

MyMap contains: {105=Sam, 104=Jo, 101=John, 103=Kim, 102=Marry}
SetView contains: [105, 104, 101, 103, 102]