-1
\$\begingroup\$

In my game, the whole thing is based off of grids. So the map is a dual dimensional array of 32 (32 x 32 grid map). Now what I want to be able to do is to grab a grid and be able to access it and alter it by using a method. To put it simply, I want a method such as Grid grid = getGrid(10, 10); and that would grab the grid at 10 x and 10 y, then when I do some basic edition to the object, it would change the object in the array as well. I don't know how to edit an object after it was changed by being grabbed by a method. I've heard about Java references and I don't know how to use it. I would like help being able to grab an object from an array, pass it on through a method, and be able to save it in another object and when that object is edited, the one in the array is edited. Thanks in advanced!

\$\endgroup\$
  • 1
    \$\begingroup\$ Something confuses me: a 32x32 map IS a grid. But when you call 'getGrid(10, 10)' you expect a 'Grid' instead of the object at that location in the grid. Please explain. \$\endgroup\$ – moby Apr 18 '13 at 9:59
  • \$\begingroup\$ I'm sorry. The block class is named Grid so getGrid(10, 10) is referring to the getting the block at that location. \$\endgroup\$ – LiquidFeline Apr 18 '13 at 10:00
3
\$\begingroup\$

From what I understand you want something like this. You can change the name and value from the Grid-object. It refers to the same object as in the array. So this works 'out of the box'. Is this what you mean?

public class Game
{
private static final int LENGTH = 32;
public Grid[][] grids = new Grid[LENGTH][LENGTH];

public Grid getGrid(final int row, final int column)
{
    if (row >= 0 && row < LENGTH && column >= 0 && column < LENGTH)
    {
        if (grids[row][column] == null)
        {
            grids[row][column] = new Grid();
        }

        return grids[row][column];
    }

    return null;
}

public static class Grid
{
    int value;
    String name;
}
\$\endgroup\$
  • \$\begingroup\$ If I edit an object I get from the method, will it also change the object in the array? I didn't quite get what you said. \$\endgroup\$ – LiquidFeline Apr 18 '13 at 10:16
  • \$\begingroup\$ Yes it does. It is the same object. Java doesn't give you an object, it gives an address location. \$\endgroup\$ – moby Apr 18 '13 at 10:18
  • \$\begingroup\$ Or you could say Java never copies objects unless you explicitly call a copying function. Of course, primitive types (like 'int', 'float') behave differently. \$\endgroup\$ – Liosan Apr 18 '13 at 10:26

Not the answer you're looking for? Browse other questions tagged or ask your own question.