EnumerationクラスでHashtableの要素の一覧を入手する


import java.util.*;
class ExmEnumeration {
      public static void main(String[] args)  {
           //Hashtable 作成
           Hashtable ht = new Hashtable();
           ht.put("program1", new PrgProfile("prgName1", "Bill"));
           ht.put("program2", new PrgProfile("prgName2", "Tobal"));
           ht.put("program3", new PrgProfile("prgName3", "Yosaku"));

           //キー値一覧を取出す場合
           Enumeration e2 = ht.keys();
           while (e2.hasMoreElements()) {
                 System.out.println(e2.nextElement());
           }
           System.out.println("\n\n");
           //要素一覧を取出す場合
           for (Enumeration e1   = ht.elements(); e1.hasMoreElements();) {
               PrgProfile  pp  = (PrgProfile)e1.nextElement();
               System.out.println(pp.getProfile());
           }
      }    // for-loopと while-loopの使い分けは特に意味はありません。
}
      
class PrgProfile  {
      private String pname;
      private String author;
      PrgProfile(String pname, String author) {
           this.pname  = pname;
           this.author = author;
      }
      public String getProfile() {
            return (pname + "  " + author);
      }
}

<実行結果>

program3
program2
program1



prgName3 Yosaku
prgName2 Tobal
prgName1 Bill

とコンソールに表示されます。

Enumerationクラス>
Hashtableを使えば、"何番目に登録されている"と言った指定(INDEX)ではなく、キーの値を指定することでデータの取り出しが可能となります。
しかし、Hashtableに格納されている内容があらかじめわからない場合もあるでしょう。
その時はHashtableオブジェクトからEnumerationクラスのオブジェクトを取り出して、そこから要素の一覧を入手します。

keysメソッド>
Hashtableからキーの一覧を持つEnumerationオブジェクトを入手します。
<elementsメソッド>
Hashtableから要素の一覧を持つEnumerationオブジェクトを入手します。
nextElementメソッド>
Enumerationオブジェクトからデータをひとつずつ取り出します。