[置顶] HashMap遍历方法

时间:2021-03-13 20:21:08
 Map map = new HashMap();
  Iterator iter = map.entrySet().iterator();
  while (iter.hasNext()) {
  Map.Entry entry = (Map.Entry) iter.next();
  Object key = entry.getKey();
  Object val = entry.getValue();
  }



Map map = new HashMap();
  Iterator iter = map.keySet().iterator();
  while (iter.hasNext()) {
  Object key = iter.next();
  Object val = map.get(key);
  }

对于keySet其实是遍历了2次,一次是转为iterator,一次就从hashmap中取出key所对应的value
而entryset只是遍历了第一次,他把key和value都放到了entry中