假设我有一个表示棋盘游戏的2D数组。我有一个“值”(键) (1,2,3. 12)的列表,表示数组中相对于当前位置的位置。
例如,在array[1][1]中,键1表示左array[1][0]的位置,而键2可能表示左边和上面的位置数组[0][0]。
有没有办法在HashMap中存储这两个数据(我想避免每次使用这些值时都会出现一堆if-语句)?或者,在任何数据结构中?现在是创建枚举的正确时机吗?
我试过了,但显然行不通。
int row = 3;
int col = 5;
HashMap<Integer,String> markMap = new HashMap<>();
markMap.put(1,"col-1");
String location = markMap.get(1);
grid[row][(int)location] = 500;发布于 2016-07-18 00:21:28
到目前为止有很好的建议。在其他人的基础上,您还可以创建一个补偿枚举。
enum Direction {
LEFT(-1, 0),
UPPERLEFT(-1, -1),
DOWN(0, - 1),
...;
public final int xoffset;
pubiic final int yoffset;
Direction(int xoffset, int yoffset) {
this.xoffset = xoffset;
this.yoffset = yoffset;
}
public static GridObject getRelativeItem(GridObject[][] grid, int x, int y, Direction dir) {
return grid[x + dir.xoffset][y + dir.yoffset];
}
public static void setRelativeItem(GridObject[][] grid, int x, int y, Direction dir, GridObject newValue) {
grid[x + dir.xoffset][y + dir.yoffset] = newValue;
}
}如果坚持此设计,则可以通过调用(如果希望访问(1,1)的左侧)访问网格项。
Direction.getRelativeItem(grid, 1, 1, LEFT)要设置,同样可以调用它来设置值:
Direction.setRelativeItem(grid, 1, 1, LEFT, myValue)虽然这很尴尬,而且无可否认的是,它散发着糟糕的抽象气息。或者,您可以为偏移量定义getter(添加只返回私有变量值的实例方法xoffset和yoffset )。然后你会有静态的物体离开,上面,向下,很像板球007的解决方案。在这种情况下,如果您想获得一个值,您可以调用
grid[x + LEFT.xoffset()][y + LEFT.yoffset()]设置
grid[x + LEFT.xoffset()][y + LEFT.yoffset()] = myValue;根据定义,您不能亲自实例化枚举。Enums are initialized by the JVM,并且只有固定的数量(在本例中是左、上、下)。
发布于 2016-07-18 00:10:08
利用OOP并制作一个对象!存储一个“增量”位置对象数组,它将是一对存储当前索引相对位置的增量-x,增量-y。
在你的例子中,
int row = 1;
int col = 1;
// one left
array[row][col] = new DeltaLocation(-1,0); // (col, row) or (x, y)
int relativeCol = col + array[row][col].getDeltaX();您可以将它们放置到Hashmap中,也可以实现DeltaLocation对象来保存值。你说了算。
发布于 2016-07-18 00:11:55
有许多解决办法是可行的。想到的一种方法是将行偏移量和列偏移量存储在两个不同的映射中。例如
int row = 3
int col = 5
HashMap<Integer, Integer> rowOffset = new HashMap<>();
HashMap<Integer, Integer> colOffset = new HashMap<>();
rowOffset.put(1, 0)
colOffset.put(1, -1)
grid[row + rowOffset.get(1)][col + colOffset.get(1)] = 500创建一个同时存储行和列偏移量的对象可能会更干净,但这应该会给您提供这样的想法。
https://stackoverflow.com/questions/38427058
复制相似问题