增强For遍历Map集合的要点!

来源:互联网 发布:个人域名有什么用 编辑:程序博客网 时间:2024/05/29 12:28
import java.util.*;class ForTest{public static void main(String[] args){HashMap<Integer,String>hm=new HashMap<Integer,String>();hm.put(1,"xxc1");hm.put(2,"xxc2");hm.put(3,"xxc3");/*Set<Integer>s=hm.keySet();for(Integer i:s){System.out.println(i+"=="+hm.get(i));}*/Set<Map.Entry<Integer,String>>s=hm.entrySet();for(Map.Entry<Integer,String> me:s){System.out.println(me.getKey()+"========"+me.getValue());}}}

注意:

1.只要是迭代器Iterator能迭代的一定能用增强For进行遍历!Map集合必须先将键或者Map.Entry键值关系存入Set集合中。

2增强For和迭代器的区别:增强For只能获取集合里的元素,不能对集合进行操作,但是迭代器Iterator能对集合进行删除!ListIterator列表迭代器还能进行增删改查操作!

3.迭代器对集合的操作会使原集合发生变化,而For循环是不会发生改变的,例如在增强For遍历时,将其他值的引用给了For。

4增强For和普通For的区别:如果要打印100次Hello World 增强For是不能完成的!所以在遍历数组时,建议用传统For!


原创粉丝点击