for循环增强

jdk1.5增强的for循环

 

增强的for循环对于遍历array或Collection的时候相当简便

  例如:

import java.util.*;

public class EnhanceFor {
	public static void main(String[] args) {
		int[] arr = {1,2,3,4,5};
		for(int i : arr) {
			System.out.println(i);
		}
		
		
		Collection c = new ArrayList();
		c.add(new String("aaa"));
		c.add(new String("bbb"));
		c.add(new String("ccc"));
		for(Object o : c) {
			System.out.println(o);
		}
	}
}

 结果如下:

1
2
3
4
5
aaa
bbb
ccc

---------------------------------------------------------------------------------------------------------------------------

缺陷:

数组:

  不能方便地访问下标值:例如删除第几个位置上的值

集合:

  与使用Iterator相比,不能方便地删除集合中的内容

    在内部也是调用Iterator

除了简单遍历并读出内容外,不建议使用增强for循环

posted @ 2019-08-15 16:16  水果、、  阅读(204)  评论(0编辑  收藏  举报