如何遍历HashTable

来源:互联网 发布:电脑主题软件 编辑:程序博客网 时间:2024/05/22 06:41
package   com.zcjl.test;  
   
  import   java.util.Hashtable;  
  import   java.util.Iterator;  
   
  public   class   TestHashtable   {  
          public   static   void   main(String[]   args)   {  
                  Hashtable   table   =   new   Hashtable();  
                  table.put("1",   "AAA");  
                  table.put("2",   "BBB");  
                  table.put("3",   "CCC");  
                  table.put("4",   "DDD");  
                  table.put("5",   "EEE");  
                  for   (Iterator   it2   =   table.keySet().iterator();   it2.hasNext();)   {  
                          String   key   =   (String)   it2.next();  
                          System.out.println(key   +   table.get(key));  
                  }  
          }  
  }  
   
  结果为  
  5EEE  
  4DDD  
  3CCC  
  2BBB  
  1AAA  
   
   
   
  package   com.zcjl.test;  
   
  import   java.util.HashMap;  
  import   java.util.Iterator;  
   
  public   class   TestHashMap   {  
          public   static   void   main(String[]   args)   {  
                  HashMap   hashMap   =   new   HashMap();  
                  hashMap.put("1",   "AAA");  
                  hashMap.put("2",   "BBB");  
                  hashMap.put("3",   "CCC");  
                  hashMap.put("4",   "DDD");  
                  hashMap.put("5",   "EEE");  
                  for   (Iterator   it   =   hashMap.keySet().iterator();   it.hasNext();)   {  
                          String   key   =   (String)   it.next();  
                          System.out.println(key   +   hashMap.get(key));  
                  }  
          }  
  }  
   
  结果为:  
  3CCC  
  5EEE  
  2BBB  
  4DDD  
  1AAA  
   
  从结果看,也许Hashtable能保证按加入的顺序遍历?  
  这个测试太简单,所以我不敢保证结论