@Test public void m1(){ HashMap<String,String> hashMap=new HashMap<>(); hashMap.put("a", "jack"); hashMap.put("b","alice"); for(Map.Entry<String,String> entry:hashMap.entrySet()){ System.out.println(entry.getKey()+"--"+entry.getValue()); } }
如题,学习遍历HashMap时想到的,老师只说for循环能遍历集合,但我想知道具体是哪些类型的集合可以遍历?还是说只要实现Collection接口都能遍历?
对于Java中的集合,只要实现了Iterable接口,就可以使用foreach循环或者迭代器进行遍历。Iterable接口继承自java.util.Collection,因此所有实现了Collection接口的集合类都可以遍历。包括但不限于ArrayList、LinkedList、HashSet、TreeSet、HashMap、TreeMap等。需要注意的是,Map接口不继承自Collection接口,因此遍遍历Map需要使用其keySet()、values()或者entrySet()方法获取其键、值或键值对的集合,然后再进行遍历。