集合中添加的内容是对象。基本类型不是对象,不属于Object。但此时jvm可以用自动装箱来完成,将其添加进去(添加进去的是对象)。[code]public class IterateTest {
public static void main(String args[]) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
for (int i : al) {
System.out.println(i);
}
}
}[/code]上面的正确,上面的虽然装进去的是基本类型。但是系统已经帮你将其自动装箱成了Integer对象了,当用foreach循环的时候,系统又会自动将其拆箱为int类型。但是,下面的就是错误的。[code]public class IterateTest {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add(1);
al.add(2);
for (int i : al) {
System.out.println(i);
}
}
}[/code]再不指定泛型类型的情况下,集合默认装的是Object类型。在迭代集合时,其中的元素是Object类型,int属于基本类型,不是Object !所以此时连编译器都不会通过。 |