Java中的哈希表 keySet() 方法及示例
Java.util.Hashtable 用于在哈希表中创建一组关键元素。它基本上返回键的集合视图,或者我们可以创建一个新集合并将键元素存储在其中。
句法:
public Set keySet()
K : 哈希表中键的类型
参数:该方法不带任何参数。
返回值:该方法返回一个具有哈希表键的集合。
下面的程序用于说明Java.util.Hashtable.keySet() 方法的工作:
示例 1:
Java
// Java code to illustrate the keySet() method
// to get Set view of Keys from a Hashtable.
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;
public class Example1 {
public static void main(String[] args)
{
// Creating an empty Hashtable
Hashtable hash_t
= new Hashtable();
// Add mappings into the table
hash_t.put("1", "Geeks");
hash_t.put("2", "For");
hash_t.put("3", "Geeks");
// Getting a Set of keys using
// keySet() method of Hashtable class
Set hash_set = hash_t.keySet();
System.out.println(
"Set created from Hashtable Keys contains :");
// Iterating through the Set of keys
Iterator itr = hash_set.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
Java
// Java code to illustrate the keySet() method
// to get Set view of Keys from a Hashtable.
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;
public class Example2 {
public static void main(String[] args)
{
// Creating an empty Hashtable
Hashtable hash_t
= new Hashtable();
// Inserting elements into the table
hash_t.put("Geeks", "1");
hash_t.put("For", "2");
hash_t.put("geeks", "3");
// Getting a Set of keys using
// keySet() method of Hashtable class
Set hash_set = hash_t.keySet();
System.out.println(
"Set created from Hashtable Keys contains :");
// Iterating through the Set of keys
Iterator itr = hash_set.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
输出
Set created from Hashtable Keys contains :
3
2
1
示例 2:
Java
// Java code to illustrate the keySet() method
// to get Set view of Keys from a Hashtable.
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Set;
public class Example2 {
public static void main(String[] args)
{
// Creating an empty Hashtable
Hashtable hash_t
= new Hashtable();
// Inserting elements into the table
hash_t.put("Geeks", "1");
hash_t.put("For", "2");
hash_t.put("geeks", "3");
// Getting a Set of keys using
// keySet() method of Hashtable class
Set hash_set = hash_t.keySet();
System.out.println(
"Set created from Hashtable Keys contains :");
// Iterating through the Set of keys
Iterator itr = hash_set.iterator();
while (itr.hasNext())
System.out.println(itr.next());
}
}
输出
Set created from Hashtable Keys contains :
For
Geeks
geeks
注意:可以对具有不同数据类型的变化和组合的任何类型的映射执行相同的操作。