我有这个代码,
class Test
{
public static void main(String args[])
{
ArrayList<Integer> al=new ArrayList<>();
al.add(1);
al.add(2);
al.add(3);
Integer a[]=new Integer[2];
al.toArray(a);
for(int i:a)
System.out.println(i);
/*for(int i=0;i<a.length;i++)
System.out.println(a[i]);*/
}
}
上面的代码抛出 NullPointerException 但如果我尝试去掉注释部分,并增强注释 for 循环,它将打印 null 2 次。打印 a.length 会打印 2。将整数数组大小设置为 3 将打印 123。
如果我错了,请纠正我:
1> 我对 toArray(T[] a) 方法的理解是,如果数组的大小小于列表中的元素,则将创建新数组,其大小由数组指定,并且其中的元素将为空,考虑到这一点。我的数组应该如下所示 a[]={null,null};
2>增强for循环与传统for循环的区别在于增强for循环中不能修改或删除单个元素。
但是,为什么这个程序会有所不同呢?我只是打印它们,为什么增强 for 循环不打印 null 并抛出 NullPointerException?
最佳答案
toArray(a)
方法返回转换后的数组,这就是您应该使用的;它没有使用您的数组,因为它不够大。
也就是说,
- 如果列表的大小为
2
(与您的数组的长度相同) 为该方法提供) 或 - 如果你的数组长度是
3
(相同 作为您想要转换为数组的列表的大小),
你不需要返回的数组;因此,您的 for
循环将打印出您想要的内容。
至于NullPointerException
,这是因为它从Integer
到int
自动拆箱。也就是说,以下代码不会抛出 NPE
:
for(Integer i : a)
{
System.out.println(i);
}
而以下代码将(就像您的情况一样):
for(int i : a)
{
System.out.println(i);
}
至于编译器为什么要使用上面的增强型 for 循环进行拆箱,请想一想 - 数组的内容是装箱的整数。您尝试将它们分配给一个primitive
int 引用(将其读作对于数组中的每个 int),因此唯一的方法是取消装箱对象的装箱。
for(int i : a)
{
System.out.println(a[i]);
}
翻译为
for(int i = 0; i < a.length; i++)
{
System.out.println((int) a[i]); // a[i] is null here, so casting causing an NPE
}
或者更准确地说,
for(int i = 0; i < a.length; i++)
{
System.out.println(a[i].intValue()); // a[i] is null here, causing an NPE
}
关于java - 使用增强型 for 循环和传统 for 循环打印从 toarray() 方法返回的数组之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26963659/