当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Hashtable keySet()用法及代码示例


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和集合概念,并做好行业准备。




相关用法


注:本文由纯净天空筛选整理自sayaliparulekar大神的英文原创作品 Hashtable keySet() Method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。