I've got an array in an array and want to initialize it with a for each loop.
// class variable
Tree[][] trees;
// in constructor
this.trees = new Tree[length][with];
// initialize
for (Tree[] tree : this.trees){
for(Tree tree2 : tree){
tree2 = new Tree();
System.out.println(tree2);
}
}
for (Tree[] tree : this.trees) {
for (Tree tree2 : tree) {
System.out.println(tree2);
}
}
What happens is that the first println prints initialized trees, so they got initialized. I thought everything is ok. But when I try to use these trees, I get a nullpointerexception. So I tried to loop through the arrays again, and the second println gives me null for every tree. How can this be? What am I missing here? Thank you!
Edit: Oh I'm very sorry, It wasn't the main but the constructor method the loops are placed.
thisin themainmethod, becausemainisstatic. Also, this codetree2 = new Tree();has no effect at all, becausetree2is just a local variable in the loop. There is no way to initialize objects the way you want with a for each loop.