Reputation: 51
protected Day[] days= new Day[n];
for(int i=0;i<days.length; i++)
{
days[i]= new Day(5);
}
Above mentioned code works fine for me but modified for loop as mentioned below results in NullPointerException when I try to access the elements of the array. Can anyone explain why does it happens?
protected Day[] days= new Day[n];
for(Day d:days)
{
d= new Day(5);
}
Upvotes: 1
Views: 78
Reputation: 726639
Loop variable in enhanced for
loop is temporary. Assigning it inside loop body has no effect on the original item. Here is what happens to the loop according to Java Language Specification:
Day[] days = ... for (int i = 0; i < days.length; i++) { Day d = days[i]; ... }
When you assign d
, it changes the local variable d
, not days[i]
, which isnearly always an error. For that reason, some programming shops adopt a practice of making loop variable of enhanced for
loop final:
for(final Day d:days) {
d= new Day(5); // <<== Compile-time error
}
If you want to shorten the code by avoiding the loop, use
Arrays.setAll(days, i -> new Day(5));
Upvotes: 1
Reputation: 315
When Java sees the enhanced for loop that you've made, it runs whatever you put inside it and makes a new variable (called d
) and gives this variable a value of whatever is inside of your array. When you set d
equal to a new Day(5);
you are changing the value of the variable d
, not the value inside the array. Here is a workaround:
protected D[] days = new Day [n];
for(int i = 0;i<days.length;i++)
days[i] = new Day(5);
This reaches into the actual array to set values. Hope this helps!
Upvotes: 1
Reputation: 665
Second type of for
uses Iterator
for iterating by elements. Initializing reference d
makes no sence, because this operation doesn't change reference inside your array.
Upvotes: 0