增强for循环

来源:互联网 发布:vs2017 连接mysql 编辑:程序博客网 时间:2024/05/16 16:19

增强for循环是JDK 5.0出现的新特性,其本质与iterator遍历的效果是一样,也就是说增强for循环的内容就是在调用iterator来实现的。

优点有:

① 使用增强for在遍历过程中,不需要检查数组的边界,更不用担心数组越界;

② 结构简洁明了,实现iterator接口的都可以使用增强for,等;

结构:

for(变量类型 变量名:需迭代的数组或集合)

{

语句;

}

缺点

① 不能在增强for循环中动态的删除改变集合内容;

② 不能获取集合的下标值,等;

注意事项

① ArrayList由于使用数组实现,因此下标明确,最好使用传统的for循环;

② LinkedList获取一个元素,要从头开始向后找,因此尖刺使用增强for循环,也就是使用iterator;

③ Map集合也可通过两种方式进行增强for循环遍历:

a)使用keyset()方法,通过iterator得到Map集合中的每一个key,在通过map.get(key)获取key对应的值;

b)通过entryset方法获取set集合。

普通数组遍历测试:

<span style="white-space:pre"></span>@Testpublic void test1(){int arr[]={1,2,3};for(int i : arr){System.out.println(i);}String arr1[]={"aaa","bbb","ccc","ddd"};for(String i:arr1){System.out.println(i);}}
list集合迭代遍历测试:

@Testpublic void test2(){List list=new ArrayList();list.add("aaa");list.add("bbb");list.add("ccc");for(Object obj:list){String str=(String) obj;System.out.println(str);}}
Map集合的传统方式迭代遍历测试:

<span style="white-space:pre"></span>@Testpublic void test3(){Map map=new HashMap();map.put(1, "a");map.put(2, "b");map.put(3, "c");Set set=map.keySet();Iterator it=set.iterator();while(it.hasNext()){int key= (Integer) it.next();String value=(String) map.get(key);System.out.println(key+"....."+value);}}@Testpublic void test4(){Map map=new HashMap();map.put(1, "aa");map.put(2, "bb");map.put(3, "cc");Set set=map.entrySet();Iterator it=set.iterator();while(it.hasNext()){Map.Entry entry=(Entry) it.next();int key=(Integer) entry.getKey();String value=(String) entry.getValue();System.out.println(key+"......."+value);}}
Map集合使用增强for循环的遍历迭代测试:

<span style="white-space:pre"></span>@Testpublic void test5(){Map map=new HashMap();map.put(1, "a");map.put(2, "b");map.put(3, "c");for(Object obj:map.keySet()){int key=(Integer) obj;String value=(String) map.get(key);System.out.println(key+"....."+value);}}@Testpublic void test6(){Map map=new HashMap();map.put(1, "aa");map.put(2, "bb");map.put(3, "cc");for(Object obj:map.entrySet()){Map.Entry entry=(Entry) obj;int key=(Integer) entry.getKey();String value=(String) entry.getValue();System.out.println(key+"...."+value);}}




1 0
原创粉丝点击