简体   繁体   English

在Java中编辑对象2D数组的字段

[英]Editing fields of an object 2d array in java

The goal is to copy some Tile objects and custom properties into a 2D array, however I got unexpected results : 目标是将一些Tile对象和自定义属性复制到2D数组中,但是我得到了意外的结果:

    for (int i = 0; i<3; i++)
    {
        for (int j = 0; j<3; j++)
        {
            TileList[i][j] = Tiles[3];
            //the goal is the overwrite the MapX and MapY fields of each element of the new Array 
            TileList[i][j].MapX = i;
            TileList[i][j].MapY = j; 
        }
    }

After printing out the values each element each MapX and MapY field of each element was expect to have their own separate value, however instead both MapX and MapY are set to 3 for each tile object reference in the 2d Array. 在打印出每个元素的值之后,每个元素的每个MapX和MapY字段均应具有各自独立的值,但是对于2d数组中的每个图块对象引用,MapX和MapY均设置为3。

You're setting all the array members to the same object with this statement: 您可以使用以下语句将所有数组成员设置为同一对象:

    TileList[i][j] = Tiles[3];

That statement copies a reference to an object, not the object itself. 该语句复制对对象的引用,而不是对象本身。

On the last pass through the loop, all the array members point to the same object, and these statements set its members to 3 and 3: 在循环的最后一次遍历中,所有数组成员都指向同一个对象,这些语句将其成员设置为3和3:

    TileList[i][j].MapX = i;
    TileList[i][j].MapY = j; 

If you want all the array members to point to different objects, you can create a new object for each with a default constructor: 如果希望所有数组成员都指向不同的对象,则可以使用默认构造函数为每个对象创建一个新对象:

    TileList[i][j] = new Tile();

Or a constructor which copies another object: 或复制另一个对象的构造函数:

    TileList[i][j] = new Tile( myDefaultTile );

Or the clone() method, if you support it: clone()方法(如果支持):

    TileList[i][j] = myDefaultTile.clone();

As an aside, note that it is customary in Java for the names of variables and class members to begin with a lowercase letter. 顺便说一句,请注意,在Java中习惯上,变量和类成员的名称以小写字母开头。 For example: 例如:

    tileList[i][j].mapX = i;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM