如何在Java中使用Enumeration顯示Hashtable的元素?


Hashtable是Java中一個強大的資料結構,允許程式設計師以鍵值對的形式儲存和組織資料。許多應用程式需要從Hashtable中檢索和顯示條目。

在Hashtable中,任何非空物件都可以作為鍵或值。但是,為了成功地從Hashtable中儲存和檢索專案,用作鍵的物件必須同時實現equals()方法和hashCode()方法。這些實現確保正確處理鍵比較和雜湊,從而能夠有效地管理和檢索Hashtable中的資料。

透過使用Hashtable中的keys()和elements()方法,我們可以訪問包含鍵和值的Enumeration物件。

透過使用諸如hasMoreElements()和nextElement()之類的列舉方法,我們可以有效地檢索與Hashtable連結的所有鍵和值,並將它們作為列舉物件獲取。這種方法允許無縫遍歷和提取Hashtable中的資料。

使用Enumeration的優點

  • 效率:在使用Hashtable等舊版集合類時,列舉效率高且輕量級,因為它不依賴於迭代器。

  • 執行緒安全:與Iterator不同,Enumeration是一個只讀介面,這使得它成為執行緒安全的,並且是多執行緒情況下的好選擇。

現在讓我們來看幾個關於如何使用Enumeration從Hashtable獲取元素的例子

示例1

import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;


public class App {
   public static void main(String[] args)
   {
      // we will firstly create a empty hashtable
      Hashtable<Integer, String> empInfo
         = new Hashtable<Integer, String>();

      // now we will insert employees data into the hashtable
      //where empId would be acting as key and name will be the value
      empInfo.put(87, "Hari");
      empInfo.put(84, "Vamsi");
      empInfo.put(72, "Rohith");

      // now let's create enumeration object
      //to get the elements which means employee names
      Enumeration<String> empNames = empInfo.elements();

      System.out.println("Employee Names");
      System.out.println("==============");
      // now we will print all the employee names using hasMoreElements() method
      while (empNames.hasMoreElements()) {
         System.out.println(empNames.nextElement());
      }
   }
}

輸出

Employee Names
==============
Hari
Vamsi
Rohith

在之前的例子中,我們只顯示了員工的姓名,現在我們將顯示員工的ID和姓名。

示例2

import java.io.*;
import java.util.Enumeration;
import java.util.Hashtable;


public class App {
   public static void main(String[] args)
   {
      // we will firstly create a empty hashtable
      Hashtable<Integer, String> empInfo
         = new Hashtable<Integer, String>();

      // now we will insert employees data into the hashtable
      //where empId would be acting as key and name will be the value
      empInfo.put(87, "Hari");
      empInfo.put(84, "Vamsi");
      empInfo.put(72, "Rohith");

      // now let's create enumeration objects
      // to store the keys
      
      Enumeration<Integer> empIDs = empInfo.keys();

      System.out.println("EmpId" + "  \t"+ "EmpName");
      System.out.println("================");
      // now we will print all the employee details
      // where key is empId and with the help of get() we will get corresponding
      // value which will be empName
      while (empIDs.hasMoreElements()) {
         int key = empIDs.nextElement();
         System.out.println( " "+ key + "  \t" + empInfo.get(key));
      }
   }
}

輸出

EmpId   EmpName
================
 87    Hari
 84    Vamsi
 72    Rohith

結論

在本文中,我們討論了Hashtable和Enumeration的概念及其優點,並且我們還看到了如何使用Enumeration從Hashtable中獲取元素以及一些示例。

更新於:2023年8月3日

363 次瀏覽

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.