简体   繁体   中英

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 :

    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.

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:

    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:

    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. For example:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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