简体   繁体   English

如何使用增强的for循环初始化数组?

[英]How can I initialize an array with an enhanced for-loop?

I was optimizing an application and wanted to change my for loops to enhanced loops: 我正在优化应用程序,并想将我的for循环更改为增强循环:

From: 从:

for (int m = 1;m < MAX_BEREN;m++)
{           
    Wasberen[m] = new Wasbeer();       
    Wasberen[m].YYY = r.nextInt(SchermY - 28);
}

to: 至:

for (Wasbeer a : Wasberen)
{
    if (a!=null)
    {
       a = new Wasbeer();
       a.YYY = r.nextInt(SchermY - 28);
    }
}

I get a NullPointerException, because it probably doesnt know how much 'beren' can be in the array, but I'm not sure how to manage the same as the loop above (MAX_BEREN = 11). 我收到一个NullPointerException,因为它可能不知道数组中可以有多少“ beren”,但是我不确定如何管理与上面的循环相同的内容(MAX_BEREN = 11)。

为了初始化数组,您应该坚持以前的语法。

如果增强的for语句中的数组引用(在这种情况下为“ Wasberen ”)为null,则在执行该语句时将导致NullPointerException

You can't use the enhanced for-loop in Java to fill an array. 您不能使用Java中增强的for循环来填充数组。 (I'm assuming your Wasberen array was already created before - if not, this will get you a NullPointerException in both variants.) (我假设您的Wasberen数组之前已经创建-如果没有,这将在两个变体中都为您提供NullPointerException。)

Your code (simplified) 您的代码(简体)

for (Wasbeer a : Wasberen)
{
    a = ...;
}

is equivalent to 相当于

for (int i = 0; i < Wasberen.length; i++)
{
    Wasbeer a = Wasberen[i];
    a = ...;
}

This assignment will change the local variable a , but will have no effect on the contents of the array. 此分配将更改局部变量a ,但不会影响数组的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM