import java.util.*;
class TestHashtable{
public static void main(String[] args){
Hashtable ht=new Hashtable();
ht.put("one",new Integer(1));
ht.put("two",new Integer(2));
ht.put("Three",new Integer(3));
ht.put("four",new Integer(4));
ht.put("five",new Integer(5));
Enumeration em=ht.keys();
while(em.hasMoreElements()){
Object key=em.nextElement();
Object value=ht.get(key);
System.out.println(""+key+"="+value);
}
}
}
對于Enumeration em=ht.keys()這句到底應該如何理解? 此程序中有哪個類實現了Enumeration接口﹐我覺得此接口中的方法體還沒在實現接口的類中定義呢﹐怎么就調用呢?還有對于Object key=em.nextElement();Object value=ht.get(key);這兩句我也不理解﹐最后此哈希表中的對象是如何列舉出來的?請各位幫幫忙﹐非常感謝﹗﹗﹗

解决方案 »

  1.   

    "Enumeration em=ht.keys()"  Hashtable 的keys方法返回一个Enumeration
    public synchronized Enumeration keys() {
    return getEnumeration(KEYS);
        }
    private Enumeration getEnumeration(int type) {
    if (count == 0) {
        return emptyEnumerator;
    } else {
        return new Enumerator(type, false);
    }
        }
      

  2.   

    Enumeration em=ht.keys();
    接口=实现此接口的实例;后面那个根据key取value
      

  3.   

    1,ht.keys() 方法是返回哈西表中的key值的列举,并赋给了变量em【Enumeration em=ht.keys()】
      

  4.   

    Object key=em.nextElement();就是取Enumeration em的下一个元素
    Object value=ht.get(key);   
     public synchronized Object get(Object key) {
    Entry tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    for (Entry e = tab[index] ; e != null ; e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
    return e.value;
        }
    }
    return null;
        }
    get(Object key)是Hashtable的方法,返回与key对应的value
    当然也可以这样写Integer value=(Integer)ht.get(key);
      

  5.   

    最后此哈希表中的對象是如何列舉出來的?
    遍历em得到:
    while(em.hasMoreElements()){
    Object key=em.nextElement();
    Object value=ht.get(key);
    System.out.println(""+key+"="+value);
    }
      

  6.   

    此程序中有哪個類實現了Enumeration接口﹐我覺得此接口中的方法體還沒在實現接口的類中定義呢﹐怎么就調用呢?
    -------
    这里是运用了对工厂方法,隐藏了对Enumeration的实现,体现了对接口编程的
    思想。这里只不过是把由ht.keys()向上转型为Enumeration类型。
    可以看看java pattern 中的工厂方法一节。
    -------
    key=em.nextElement()
    -------
    这个是Enumeration声明的方法,每个具体实现都应该实现该方法
    -------
    Object value=ht.get(key)
    -------
    可以看看Api中HashTable
    -------