增强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
- 增强的for循环
- 增强for循环
- 增强for循环
- JAVA增强for循环
- 7.3 增强for循环
- 04.for循环增强
- 增强的for循环
- 增强for循环
- java 增强 for循环
- 增强for循环
- 增强for循环
- 增强for循环用法
- 增强For循环
- JAVA 增强for 循环
- Map 增强for循环
- 增强For循环
- 增强for循环
- 增强for循环用法
- Ubuntu14.10:Install Apache,PHP,Mysql以及扩展库
- Altium Designer PCB导入后 元件移动后全部变绿
- ubuntu批量修改文件后缀名
- 黑马程序员——其他系统对象
- Altium designer 使用心得--常用规则设置
- 增强for循环
- 基于Java的OJ(Onlie Judge)总体设计(转载)
- 狗刨学习网报道:Netmarble与NCsoft互买股票 将合作手游
- ES-Computing EditPlus 3.80.805 x86/x64
- bzoj1336/1337/2823 最小圆覆盖 计算几何
- 欢迎使用CSDN-markdown编辑器
- 什么是叫委托,委托的意义和作用
- MySQL5.5加主键锁读问题
- C++构造数据类型----指针