增强for循环的限制条件:当遍历集合或者是数组的时候,如果需要访问集合或者是数组的下标,那么最好使用普通的遍历形式,此时增强for循环时候非常不变。
代码演示
package test2;
public class Test3 {
public static void main(String[] args) {
int [] arr = new int[]{1,2,3,4,5};
for(int i = 0;i<arr.length;i++ )
{
System.out.println(arr[i]);
}
System.out.println("------------------");
for(int i:arr)
{
System.out.println(i);
}
}
}
public class Test3 {
public static void main(String[] args) {
people[] str = new people[3];
str[0]=new people("luochuang");
str[1]=new people("luochuang1");
str[2]=new people("luochuang2");
for(people str1:str)
{
System.out.println(str1.name);
}
}
}
class people
{
String name ;
people(String name )
{
this.name=name;
}
}
自动装箱与拆箱
代码示例:
import java.util.ArrayList;
public class Test4 {
public static void main(String[] args) {
ArrayList<Integer> str = new ArrayList<Integer>();
str.add(1);
str.add(2+6);
str.add(3);
for(Integer str1:str)
{
System.out.println(str1);
}
}
}
注意类型的转化。