java.util.Hashtable.keySet() 方法返回此映射中包含的键的 Set 视图。该集合由map支持,因此对map的更改会反映在集合中,反之亦然。
语法
public Set<K> keySet()
这里,K是容器维护的密钥类型。
参数
无参数必需。
返回值
返回此映射中包含的键的集合视图。
异常
不适用
示例:
在下面的示例中,java.util.Hashtable.keySet() 方法返回给定哈希表中包含的键。
import java.util.*;
public class MyClass {
public static void main(String[] args) {
//创建哈希表
Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();
//填充哈希表
Htable.put(101, "John");
Htable.put(102, "Marry");
Htable.put(103, "Kim");
Htable.put(104, "Jo");
Htable.put(105, "Sam");
//打印哈希表的内容
System.out.println("Htable contains: " + Htable);
//创建哈希表键的集合视图
Set SetView = Htable.keySet();
//打印按键设置视图
System.out.println("SetView contains: " + SetView);
}
}
上述代码的输出将是:
Htable contains: {105=Sam, 104=Jo, 103=Kim, 102=Marry, 101=John}
SetView contains: [105, 104, 103, 102, 101]