Java core didn't stay initialized
I have an array in an array and you want to initialize it with 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 were initialized. I thought it was okay. But when I try to use these trees, I get a nullpointer exception. So I tried to iterate over the arrays again and the second println gave me null for each tree. How can it be? What am I missing here? Thank!
Edit: Oh, I'm really sorry, this was not the main one, but the constructor method where the loops are placed.
source to share
Your problem is in the first loop:
tree2 = new Tree();
This line does create an instance Tree
, but stores it in a local variable tree2
instead of an array element this.trees
.
You have to loop over the array using inexed for loop:
for (int i = 0; i < trees.length; i++) {
for (int j = 0; j < trees[i].length; j++) {
threes[i][j] = new Tree();
}
}
The difference between lines threes[i][j] = new Tree();
and tree = new Tree();
is what keeps the first copy of the array element, and the second one stores it in a variable.
Java references are not C pointers. The purpose of objects is to assign a reference by value.
source to share
tree2
is a local variable (accessible in the loop scope), you are assigning the newly created instance of Tree
this variable not to your array. Then you print the contents of that variable to make it work ...
Instead, you need to explicitly store the instance in trees
, for example:
for (int l = 0; l < length; l++){
for(int h = 0; h < height; h++) {
trees[l][h] = new Tree();
System.out.println(trees[l][h]);
}
}
As you can see, it stores the instance in an array and uses the array to print the value.
source to share
As per my comment above, this:
for (Tree[] tree : this.trees){
for(Tree tree2 : tree){
tree2 = new Tree(); // changes tha variable tree2, does not touch the array.
System.out.println(tree2);
}
}
does not affect. You need
for (int i = 0; i < length; i++) {
for (int j = 0; j < width; j++) {
trees[i][j] = new Tree(); // obviously changes the array content.
}
}
source to share