Domanda

So I need to copy an instance for a method and must return an instance.

My issue is that this object consists of an array and need to copy everything in this array as well.

The class constructor only specifies the width and height of the 2d array and this class constructor cannot be altered.

How can I create a copy? The following I assume won't work because it only copies the size of array right?

public Grid copyGrid (Grid grid) {
        return new Grid(height, width);
    }
È stato utile?

Soluzione 2

You need to copy the elements yourself.

public Grid copyGrid (Grid grid) {
  Grid newGrid = new Grid(height, width);
  for (int row = 0; row < height; row++) {
    for (int col = 0; col < width; col++) {
      newGrid.getArray()[row][col] = grid.getArray()[row][col];
    }
  }
  return newGrid;
}

Altri suggerimenti

You need to make sure you have access to all the data of the Grid object (i.e. getters and setters are available). Depending on the type of methods you have, your code could look like this for example.

public Grid copyGrid(Grid grid) {
    Grid g = new Grid(grid.getHeight(), grid.getWidth());

    for (int row = 0; row < height; row++) {
        for (int col = 0; col < width; col++) {
            g.setValue(row, col, grid.getValue(row, col));
    }
    return g;
}

Assuming that you can get and set individual values within the grid.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top