The Java array does not remain initialized

I have an array in an array and want to initialize it with 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 the initialized tree, so they are initialized I think everything is fine But when I tried to use these trees, I got a NullPointerException So I tried to traverse the array again, and the second println provided null for each tree How did this happen? What did I miss here? thank you!

Editor: Oh, I'm sorry, this is not the main method, but the construction method of circular placement

Solution

Your problem occurs in the first cycle:

tree2 = new Tree();

This line does create an instance of the tree, but it stores it in the local variable Tree2 instead of the array this In the element of trees

You should use an array that does not accept for loop iterations:

for (int i = 0; i < trees.length; i++) {
    for (int j = 0; j < trees[i].length; j++) {
        threes[i][j] = new Tree();
    }
}

The third line [i] [J] = new tree(); And tree = new tree(); Is the first to store an instance in an array element and the second to store it in a single variable

Java references are not C pointers The assignment of objects is to assign references by value

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>