public static void main(String[] args){
HashMap<Integer,Integer> hashMap = new HashMap<Integer, Integer>();
hashMap.put(1, 1);
hashMap.put(2, 2);
//* 4种hashMap循环方式
// for each map.entrySet()
for(Entry<Integer, Integer> entry : hashMap.entrySet()){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
//for each map.entrySet(),用临时变量保存map.entrySet()
Set<Entry<Integer, Integer>> maps = hashMap.entrySet();
for(Entry<Integer, Integer> entry : maps){
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
//显示调用map.entrySet()的集合迭代器
Iterator<Entry<Integer, Integer>> iterator2 = hashMap.entrySet().iterator();
while(iterator2.hasNext()){
Entry<Integer, Integer> entry = iterator2.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
// for each map.keySet(),再调用get获取
for(Integer key : hashMap.keySet()){
System.out.println(key);
System.out.println(hashMap.get(key));
}
}
HashMap的四种循环遍历方式
最新推荐文章于 2024-09-16 10:28:26 发布