當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Hashtable elements()用法及代碼示例


Java中Hashtable類的java.util.Hashtable.elements()方法用於獲取哈希表中存在的值的枚舉。

用法:

Enumeration enu = Hash_table.elements()

參數:該方法不帶任何參數。


返回值:該方法返回哈希表的值的枚舉。

以下程序用於說明java.util.Hashtable.elements()方法的用法:
示例1:

// Java code to illustrate the elements() method 
import java.util.*; 
  
public class Hash_Table_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty Hashtable 
        Hashtable<Integer, String> hash_table =  
                    new Hashtable<Integer, String>(); 
  
        // Inserting elements into the table 
        hash_table.put(10, "Geeks"); 
        hash_table.put(15, "4"); 
        hash_table.put(20, "Geeks"); 
        hash_table.put(25, "Welcomes"); 
        hash_table.put(30, "You"); 
  
        // Displaying the Hashtable 
        System.out.println("The Table is: " + hash_table); 
  
        // Creating an empty enumeration to store 
        Enumeration enu = hash_table.elements(); 
  
        System.out.println("The enumeration of values are:"); 
  
        // Displaying the Enumeration 
        while (enu.hasMoreElements()) { 
            System.out.println(enu.nextElement()); 
        } 
    } 
}
輸出:
The Table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
The enumeration of values are:
Geeks
Geeks
You
4
Welcomes

程序2:強>

// Java code to illustrate the elements() method 
import java.util.*; 
  
public class Hash_Table_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty Hashtable 
        Hashtable<String, Integer> hash_table =  
                   new Hashtable<String, Integer>(); 
  
        // Inserting elements into the table 
        hash_table.put("Geeks", 10); 
        hash_table.put("4", 15); 
        hash_table.put("Geeks", 20); 
        hash_table.put("Welcomes", 25); 
        hash_table.put("You", 30); 
  
        // Displaying the Hashtable 
        System.out.println("The Table is: " + hash_table); 
  
        // Creating an empty enumeration to store 
        Enumeration enu = hash_table.elements(); 
  
        System.out.println("The enumeration of values are:"); 
  
        // Displaying the Enumeration 
        while (enu.hasMoreElements()) { 
            System.out.println(enu.nextElement()); 
        } 
    } 
}
輸出:
The Table is: {You=30, Welcomes=25, 4=15, Geeks=20}
The enumeration of values are:
30
25
15
20


相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 Hashtable elements() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。