1

I was optimizing an application and wanted to change my for loops to enhanced loops:

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).

3 Answers 3

1

If the array reference ('Wasberen' in this case) in an enhanced for statement is null, then a NullPointerException will result when the statement is executed.

Sign up to request clarification or add additional context in comments.

2 Comments

So I initialize with the 'for' and iterate in later stages with the enhanced loop? Because the 'wasberen' already exist after init
The NullPointerException could be thrown, given your snippet, from the Wasbeer no-arg constructor or if 'r' is a null reference as well. The stack trace for the exception should identify the culprit.
1

For initializing arrays, you should stick to the syntax you had before.

1 Comment

a[i] = new Object(); is not equal to Object b = a[i]; b = new Object();
1

You can't use the enhanced for-loop in Java to fill an array. (I'm assuming your Wasberen array was already created before - if not, this will get you a NullPointerException in both variants.)

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.