Dictionary เป็น abstract class แทนคู่ key/value ทำงานคล้าย Map เป็น legacy class ใน Java มีเมธอดสำคัญ 2 ตัวคือ Dictionary.keys() และ Dictionary.elements() ที่วนลูปได้ด้วย Enumeration เมธอดสำคัญอื่นๆ ได้แก่ isEmpty(), get(), remove(), size()
ไวยากรณ์
public abstract class Dictionary<K,V> extends Object
ตัวอย่าง
import java.util.*;
public class DictionaryTest {
public static void main(String[] args) {
Dictionary<Integer, String> dic = new Hashtable<Integer, String>();
dic.put(1, "Adithya");
dic.put(2, "Jaidev");
dic.put(3, "Raja");
Enumeration<Integer> key = dic.keys();
while(key.hasMoreElements()) {
System.out.println(key.nextElement());
}
Enumeration<String> element = dic.elements();
while(element.hasMoreElements()) {
System.out.println(element.nextElement());
}
}
}
ผลลัพธ์
3 2 1 Raja Jaidev Adithya