增强的for循环

for(:)这是循环遍历数组的一种方式,通常称为“增强的for循环”。

意思大概是:把a类型的集合c中的每个元素赋值给b.最常用的用于list的逐行赋值

1

2

3

4

5

6

List<String> strs = new ArrayList<String>();

strs.add("hello");

strs.add("world"); 

扫描二维码关注公众号,回复: 3696360 查看本文章

for( String s : strs){  //把strs中的每个元素依次赋值给s。第一次吧hello复制给s

    System.out.println(s); //     第一次输出hello,第二次输出world

}

所以此程序的输出结果是:

1

2

hello

world

执行过程与下面的程序是一个意思:

1

2

3

4

int size = strs.size();

for(int i =0 ; i < size; i++){

    System.out.println(strs.get(i)); 

}

猜你喜欢

转载自blog.csdn.net/liyuzhe1998/article/details/83210799
今日推荐