我有这个密码,
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,但是如果我尝试去掉注释部分,并且注释增强为循环,它将打印null 2次。打印a.length打印2。将整数数组大小设置为3将打印123。
如果我错了,现在纠正我:
1>我对toArray(T[] a)方法的理解是,如果数组的大小小于列表中的元素,则将创建具有数组指定大小的新数组,其中的元素将为空。我的数组应该类似于这个a[]={null,null};
增强的for循环与传统的for循环之间的2>区别在于,不能修改或删除增强型for循环中的单个元素。
但是,为什么这个计划会有所不同呢?我只是打印它们,为什么增强的for循环不打印空和抛出NullPointerException?
发布于 2014-11-17 00:30:56
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循环来取消装箱,请考虑一下-数组的内容是boxed整数。您尝试将它们分配给一个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
}发布于 2014-11-17 01:07:28
public <T> T[] toArray(T[] a)它以数组作为参数来复制所有元素并返回该数组。如果您的数组足够大,那么它就会对该数组进行复制,否则将在运行时为此目的分配相同的新数组。在您的示例中,大小为2的数组为2,因此创建了大小为3的新数组,并将值复制到这个新数组并返回。
第二件事,你打印ai而不是i,因为我包含元素值,所以打印i。
就像这样:
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];
a=al.toArray(a);
for(Integer i:a) //or for(int i:a)
System.out.println(i);
}https://stackoverflow.com/questions/26963659
复制相似问题