java.util.Hashtable用於在哈希表中創建一組關鍵元素。它本質上返回鍵的集合視圖,或者我們可以創建一個新集合並將鍵元素存儲在其中。
用法:
public Set<K> 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<String, String> hash_t
= new Hashtable<String, String>();
// 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());
}
}
輸出
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<String, String> hash_t
= new Hashtable<String, String>();
// 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
注意:可以對具有不同數據類型的變化和組合的任何類型的映射執行相同的操作。
注意讀者!現在不要停止學習。以student-friendly的價格掌握Java和Java集合基礎知識課程中所有重要的Java和集合概念,並做好行業準備。
相關用法
- Java Provider keySet()用法及代碼示例
- Java AbstractMap keySet()用法及代碼示例
- Java ConcurrentHashMap keySet()用法及代碼示例
- Java SortedMap keySet()用法及代碼示例
- Java Map keySet()用法及代碼示例
- Java Properties keySet()用法及代碼示例
- Java WeakHashMap keySet()用法及代碼示例
- Java HashMap keySet()用法及代碼示例
- Java TreeMap keySet()用法及代碼示例
- Java EnumMap keySet()用法及代碼示例
- Java IdentityHashMap keySet()用法及代碼示例
- Java HashTable compute()用法及代碼示例
- Java Hashtable computeIfAbsent()用法及代碼示例
- Java HashTable putIfAbsent()用法及代碼示例
- Java HashTable forEach()用法及代碼示例
- Java Hashtable toString()用法及代碼示例
- Java Hashtable elements()用法及代碼示例
- Java Hashtable keys()用法及代碼示例
- Java Hashtable containsValue()用法及代碼示例
注:本文由純淨天空篩選整理自sayaliparulekar大神的英文原創作品 Hashtable keySet() Method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。