接循环遍历整个hashMap,hashTable

来源:互联网 发布:程序员女生性格 编辑:程序博客网 时间:2024/06/06 05:43
 发现HashMap 用到下面的格式 ,直接循环遍历整个hashMap  hashTable

返回的 set 中的每个元素都是一个 Map.Entry 类型。

Java代码
private Hashtable<String, String> emails = new Hashtable<String, String>();   
  1.   
  2. //    方法一: 用entrySet()   
  3. //    Iterator it = emails.entrySet().iterator();  
  4. //    while(it.hasNext()){   
  5. //        Map.Entry m=(Map.Entry)it.next();  
  6. //        logger.info("email-" + m.getKey() + ":" + m.getValue());  
  7. //    }   
  8.      
  9.   // 方法二:直接再循环中   
  10.   for (Map.Entry<String, String> m : emails.entrySet()) {   
  11.       logger.info("email-" + m.getKey() + ":" + m.getValue());   
  12.   }   
  13.      
  14.   // 方法三:用keySet()   
  15.   Iterator it = emails.keySet().iterator();   
  16.   while (it.hasNext()){   
  17.       String key;   
  18.       key=(String)it.next();   
  19.       logger.info("email-" + key + ":" + emails.get(key));   
  20.   }  


另外 我们可以先把hashMap 转为集合Collection,再迭代输出,不过得到的对象

Java代码
  1. Map aa = new HashMap();      
  2.  aa.put("tmp1"new Object());     //追加     替换用同样的函数.     
  3.  aa.remove("temp1");   //删除     
  4.  for(Iterator i = aa.values().iterator(); i.hasNext();)   {      
  5.       Object temp =  i.next();      
  6.  }         //遍历