-1

If I have a class called cell, how could I create cell objects in a coordinate plane? (i.e. cell 1,1 is at x = 1 and y = 1). I would need to be able to access certain cells in the plane (i.e calling the cell at 2, 4 and getting info from it). I was thinking about being able to call it in a way like cell[x, y].

The cells have different states that are compared to the cells around them so I need a way to call specific cells in the coordinate plane.

Andy Thomas
  • 78,842
  • 10
  • 93
  • 142
Eclipse999
  • 23
  • 4

1 Answers1

1

You can create a class Cell with attributes x and y

public class Cell {
    private int x;
    private int y;

    public Cell(int x, int y) {
        this.x = x;
        this.y = y;
    }

    // Getter and setter as needed
}

And to know if a Cell exists in a particular point you can use different approaches:

  • Use a bidimensional array of Cell
  • Use a Map<String, Cell> where String is a key in the form x + "$" + y
  • Create a Coordinate class and use a Map<Coordinate, Cell>

Choosing between a bidimensional array and a Map depends on how sparse is your matrix. If you have a very big range of x and y and few cells use a Map, instead if you have a relative little range of coordinates use a bidimensional array.

Note creating the Coordinate class you need to remember to rewrite both .equals() and .hashCode() methods.

Davide Lorenzo MARINO
  • 22,769
  • 4
  • 33
  • 48
  • +1 for thinking about the sparse matrix case. However, depending on the use case, there may be a good argument that a `Cell` should not have its coordinates as part of its state. Otherwise the same info is recorded in two places: the cell's key/position in matrix and in the cell itself. This complicates operations like moving cells around and makes impossible a cell being in two places at once. Even the use case where you are given a random cell and need to recover the coordinates can be handled by a reverse map rather than with embedded coordinates. – Ted Hopp Jan 15 '16 at 17:09
  • @Ted Yes, you are right, but I don't know if they need or not info related to the position in the cell. Using a Coordinate class is better because the key and the position inside the Cell Class can share the same object Coordinate. – Davide Lorenzo MARINO Jan 15 '16 at 17:13
  • That doesn't solve the problem of moving cells around. If a `Coordinate` object is going to be used as the key, it needs to be immutable if you want the `Map` to behave properly. (See, e.g., [this thread](http://stackoverflow.com/questions/7842049/are-mutable-hashmap-keys-a-dangerous-practice).) That means that moving a cell requires both changing the map and (in case of a shared object) updating the `Coordinate` reference in the `Cell` object itself. – Ted Hopp Jan 15 '16 at 17:15