foreach比for的好处和弊端
好处:相对于for来说方便了对容器的遍历
弊端:没有索引,不能操作元素中的元素
格式如下:
for(元素类型 元素变量x:遍历对象(数组或集合)){
引用元素变量x的语句;
}
遍历数组实例如下:
public class DemoForEach {
public static void function() {
int[] a={0,1,2,3,4,5};
for(int x:a){
System.out.println(x);
}
}
public static void function_1() {
String[] str = { "abc", "a2bb", "a2aa" };
for (String s : str) {
System.out.println(s.length());
System.out.println(s);
}
}