Reputation: 1268
I have this code that does not work:
Panel[] panelArr = new Panel[5];
for (Panel p:panelArr) {
p = new Panel();
}
Label lblName = new Label("Name:");
panelArr[0].add(lblName);
It comes up with the error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUIVehicles$NewSportsCarDialog.<init>(GUIVehicles.java:65)
However if I replace the for-each loop with this for loop it works.
for (int i = 0; i < 5; i++) {
panelArr[i] = new Panel();
}
As far as I can tell looking through the documentation for the for each loop both for loops should be equivalent. Clearly this is not the case and I was wondering why?
Upvotes: 2
Views: 156
Reputation: 1295
In first loop you don't put objects to array. You just iterate over array which has 5 nulls, create local variable Panel p
(which points to null
) and assign a new Panel
object.
After this loop array still contains 5 nulls.
If you don't have to stick with array, use list instead:
List<Panel> panelList = new ArrayList<>(5); //Java7 diamond operator
panelList.add(new Panel());
panelList.add(new Panel());
panelList.add(new Panel());
panelList.add(new Panel());
panelList.add(new Panel());
Of course this is not the most elegant way but you will not get NPE.
Upvotes: 0
Reputation: 39457
Because p
is a local variable, it is not panelArr[i]
directly.
In your first loop you basically assign
the new Panel to p
, not to panelArr[i]
.
Think of p
and panelArr[i]
as two variables pointing
to objects of type Panel
. The fact that you initialize
p
does not mean you also initialized panelArr[i]
.
Upvotes: 0
Reputation: 129507
Your for-each is analogous to this:
for (int i = 0; i < 5; i++) {
Panel p = panelArr[i];
p = new Panel();
}
Hence the assignment to p
clearly has no effect on the array itself -- you're just redirecting p
to point somewhere else, which has no bearing on the array. So at the end of the for-each loop, all the array elements are still null
. Your second snippet is the appropriate way to fill the array.
Upvotes: 8