手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

Java中遍历HashMap的方法

[日期:2012-11-10] 来源:Linux社区  作者:Linux [字体:大 中 小]

Java中,通常有两种遍历HashMap的方法,如下:

  1. import java.util.*;
  2. publicclass MapTest {
  3. static HashMap<String, Integer> hashMap = new HashMap<String, Integer>();
  4. publicstaticvoid main(String [] args) {
  5. hashMap.put("one", 1);
  6. hashMap.put("two", 2);
  7. hashMap.put("three", 3);
  8. hashMap.put("four", 4);
  9. hashMap.put("five", 5);
  10. Iterator iter = hashMap.entrySet().iterator();
  11. // the first method to travel the map
  12. while (iter.hasNext()) {
  13. Map.Entry<String, Integer> entry = (Map.Entry<String, Integer>) iter.next();
  14. String key = entry.getKey();
  15. Integer value = entry.getValue();
  16. System.out.println(key + " " + value);
  17. }
  18. iter = hashMap.keySet().iterator();
  19. // the second method to travel the map
  20. while (iter.hasNext()) {
  21. String key = (String) iter.next();
  22. Integer value = hashMap.get(key);
  23. System.out.println(key + " " + value);
  24. }
  25. } // close main()
  26. }

第一种效率要高于第二种,应尽量使用第一种进行遍历。

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款