2013-01-24 48 views
3

我已经在数组中有一个数组,并且想要为每个循环初始化一个数组。Java数组未保持初始化

// 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); 
    } 
} 

会发生什么是第一个println打印初始化树,所以他们得到初始化。我认为一切都很好。但是当我尝试使用这些树时,我得到了一个nullpointerexception。所以我试着再次遍历数组,第二个println为每棵树都给出了null。怎么会这样?我在这里错过了什么?谢谢!

编辑:哦,我很抱歉,这不是主要的,但循环放置的构造函数方法。

+4

你不能在'main'方法中使用'this',因为'main'是'static'。此外,这个代码'tree2 = new Tree();'完全没有效果,因为'tree2'只是循环中的一个局部变量。没有办法按照你想要的方式用每个循环来初始化对象。 – jlordo

回答

1

你的问题是在第一个循环:

tree2 = new Tree();

此行确实创建的Tree实例,但它存储在本地变量tree2,而不是在阵列this.trees的元素。

您应该使用inexed for循环遍历数组:

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

线threes[i][j] = new Tree();tree = new Tree();之间的区别在于,第一存储在第二存储在单个变量数组的元素和实例。

Java引用不是C指针。对象的分配是按值分配引用。

在此
+0

很好的解释!感谢你们所有人。 – Linus

3

tree2是一个局部变量(可在范围内循环),则新创建的Tree实例分配给变量不是你的阵列。接下来,您打印的变量所以它似乎工作内容...

相反,你需要的情况下明确地存储到trees,像这样:

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]); 
    } 
} 

正如你所看到的,IT卖场数组中的实例并使用数组来打印该值。

2

按照我上面的评论,这样的:

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); 
    } 
} 

没有效果。您需要

for (int i = 0; i < length; i++) { 
    for (int j = 0; j < width; j++) { 
     trees[i][j] = new Tree(); // obviously changes the array content. 
    } 
} 
1

for循环

for(Tree tree2 : tree) 
{ 
    tree2 = new Tree(); 

你正在做分配给本地参考变量tree2,其中为tree[i][j]没有得到分配任何价值。