package com.xing.lab.util; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; public class TraverseHashTable { public static void main(String[] args) { Hashtable<String, String> hashtable = new Hashtable<String, String>(); hashtable.put("1", "aa"); hashtable.put("2", "bb"); hashtable.put("3", "cc"); //第一種hashtable遍歷方式 System.out.println("第一種遍歷方式"); for (Iterator<String> iterator = hashtable.keySet().iterator();iterator.hasNext();) { String key = iterator.next(); System.out.println("key-----" + key); System.out.println("value--------" + hashtable.get(key)); } //第二種hashtable遍歷方式 System.out.println("第二種遍歷方式"); for (Iterator<Entry<String, String>> iterator = hashtable.entrySet().iterator(); iterator.hasNext();) { Entry<String, String> entry = iterator.next(); System.out.println("key---------" + entry.getKey()); System.out.println("value------------" + entry.getValue()); } //第三種hashtable遍歷方式 System.out.println("第三種遍歷方式"); for (Map.Entry<String, String> entry : hashtable.entrySet()) { System.out.println("key---------" + entry.getKey()); System.out.println("value--------" + entry.getValue()); } //第四種遍歷方式 System.out.println("第四種遍歷方式"); Enumeration<String> e = hashtable.keys(); while (e.hasMoreElements()) { String key = e.nextElement(); System.out.println("key-----" + key); System.out.println("value-------" + hashtable.get(key)); } //第五中遍歷方式(獲取全部的值) System.out.println("第五種遍歷方式"); Enumeration<String> e2 = hashtable.elements(); while (e2.hasMoreElements()) { String string = (String) e2.nextElement(); System.out.println(string); } } }