一、增强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循环的话,相对麻烦。因此,当访问集合或数组中特定元素时,用一般的循环方法。
本文介绍了增强for循环的基本语法和使用场景,并通过多个示例详细解释了如何使用增强for循环来遍历数组和集合。同时,文章还对比了增强for循环与普通for循环的区别,以及在何种情况下更适合使用增强for循环。

281

被折叠的 条评论
为什么被折叠?



