I have a class that has an ArrayList attribute, and another class that has a 2D Array of that class:
public class someThingsList {
private List<someThings> lst;
public someThingsList () {
this.lst = new ArrayList<someThings>();
}
public addThing(someThings) {
someThings s = someThings;
this.lst.add(s);
}
}
and
public class x implements y {
private static someThingsList[][] field;
public x(int h, int w) {
x.field = new someThingsList[h][w];
for (someThingsList[] lst1 : x.field)
for (someThingsList lst2 : lst1)
lst2 = new someThingsList();
}
and when I have for example a new x object with (2,2) as h and w, and try to do
x.fields[0][0].addThing(thing);
I get a NullPointerException error, any idea why?
Unfortunately you can’t use enhanced for-each loop with arrays when you want to mutate them.
lst2in your example is just another reference (tonull), modifying it won’t modify the original array. Try this:or alternatively:
As a matter of fact, this problem is not specific to arrays. Check the following code:
Even though it looks as if you were modifying the original
stringslist, you are barely modifing temporarysvariable that is recreated and ignore after each loop.