JDK5.0新特性:For—Each增强型for循环

来源:互联网 发布:西雅图房价 知乎 编辑:程序博客网 时间:2024/06/07 07:42

一、增强for循环的语法

for(type element :  array)

{

System.out.println(element);

}

type表示循环操作目标的参数类型,element为定义的一个变量(变量类型为array中元素的类型),array表示当前遍历(只能是:数组或集合)的引用。

在循环体中,操作element就可以实现对array引用的遍历。


二、增强for循环和普通for循环的对比

例如:

class ForTest 
{
public static void main(String[] args) 
{
int[] in = new int[]{1,2,3,4,5};
for(int i = 0;i< in.length; i++)//普通循环
{
System.out.println(in[i]);
}
System.out.println("------------------");
for(int i : in)//增强型for循环
{
System.out.println(i);
}
}
}

总结:增强型For循环不是功能上增强了,是代码简化了。


三、示例

1、打印数组元素

class ForTest 
{
public static void main(String[] args) 
{
int[] in = new int[]{1,2,3,4,5};


for(int i : in)//增强型for循环。因为int中元素类型为int型变量,因此element也应定义成int型
{
System.out.println(i);
}
}
}

2、打印二维数组元素

class ForTest 
{
public static void main(String[] args) 
{
int[][] in = new int[][]{{1,2,3},{4,2,3},{9,5,8}};

for(int[] i : in)//增强型for循环。因为in中的元素类型为int型的一维数组,因此element也应定义成int 型的一维数组
{
for(int j : i)//增强型for循环。因为i中的元素类型为int型,因此element也应定义成int 型
{
System.out.println(j);
}

}
}
}

3、打印字符串数组中的元素

class ForTest 
{
public static void main(String[] args) 
{
String str[] = {"lpp","123","fgs"};

for(String s : str)//增强型for循环,str中元素为字符串型的,因此element也应定义为String类型的
{
System.out.println(s);

}
}
}

4、打印一个集合ArrayList中的元素

import java.util.*;

class ForTest 
{
public static void main(String[] args) 
{
List<String> list = new ArrayList<String>();
list.add("welcome ");
list.add("to ");
list.add("China!");

for(String str: list)//增强型for循环。因为list中的元素时String类型的,因此element也应该定义为String类型的

{
System.out.println(str);

}
}
}

三、限制条件

当遍历集合或数组时,如果需要访问集合或数组的下标,用增强For循环的话,相对麻烦。因此,当访问集合或数组中特定元素时,用一般的循环方法。


0 0
原创粉丝点击