• Java 資料結構教程

遍歷雜湊表



HashTable 類提供了一個名為 keys() 的方法,該方法返回一個列舉物件,其中包含雜湊表中的所有鍵。

使用此方法獲取鍵,並使用get()方法檢索每個鍵的值。

Enumeration(介面)的hasMoreElements()方法在列舉物件還有更多元素時返回 true。您可以使用此方法執行迴圈。

示例

import java.util.Enumeration;
import java.util.Hashtable;

public class Loopthrough {
   public static void main(String args[]) {
      String str;
      Hashtable hashTable = new Hashtable();
      hashTable.put("Ram", 94.6);
      hashTable.put("Rahim", 92);
      hashTable.put("Robert", 85);
      hashTable.put("Roja", 93);
      hashTable.put("Raja", 75);
      
      Enumeration keys = hashTable.keys();
      System.out.println("Contents of the hash table are :");
      
      while(keys.hasMoreElements()) {
         str = (String) keys.nextElement();
         System.out.println(str + ": " + hashTable.get(str));
      }       
   }
}

輸出

Contents of the hash table are :
Rahim: 92
Roja: 93
Raja: 75
Ram: 94.6
Robert: 85
廣告

© . All rights reserved.