如何在网格的单元格中存储多个对象

时间:2017-04-22 17:39:45

标签: java arrays list linked-list hashmap

背景:我有一个基于网格的棋盘游戏,可以将各种对象放到网格上。目前,您只能在阵列中存储的任何单个位置中拥有一个对象。还有一个Location类,用于映射每个对象的当前位置。物体可以在棋盘上移动并运行各种动作,但它们永远不会相互重叠。我希望能够让对象在彼此之上。

下面我有一个类,它构建一个行和列的网格,目前每个单元格只包含一个对象。我试图弄清楚我如何能够为每个单元存储多个对象而不仅仅是一个?

这样做的原因是,在构建网格时,任何时候都只能将一个对象放置在一个单元格上。我正在考虑使用List来存储对象,但是我将如何实现它呢?

/**
 * Represent a grid of cells.
 * Each cell is able to store a single object.
 * TODO: Needs to be multiple objects in a single cell
 */

public class Cell
{

 // A random number generator for providing random locations.
 private static final Random rand = Randomizer.getRandom();

 // The rows and cols of the grid.
 private int rows, cols;

private Object[][] cell;

 /**
  * Create a grid of the given values.
  * @param rows The rows of the cell.
  * @param cols The cols of the cell.
  */
 public Cell(int rows, int cols )
 {
    this.rows = rows;
    this.cols = cols;
    cell = new Object[rows][cols];
 }

 public void clear() 
 {
    for(int row = 0; row < rows; row++) {
        for(int col = 0; col < cols; col++) {
            cell[row][col] = null;
        }
    }
 }

 /**
  * Place an Object at the given location.
  * If there is already an Object at the location 
  * TODO: NEEDS TO BE ABLE TO STORE MULTIPLE OBJECTS
  * @param Object The Object to be placed.
  */
 public void place(Object object) {
    Location location = object.getLocation();
    cell[location.getRow()][location.getCol()] = object;
 }

 public Object getObjectAt(int row, int col)
 {
    return cell[row][col];
 }

 public int getRows()
 {
    return rows;
 }

 public int getCols()
 {
    return cols;
 }
}

0 个答案:

没有答案