假设我有一个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;
最佳答案
到目前为止,很棒的建议。在其他所有人的基础上,您还可以创建一个偏移量枚举
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)
尽管这很尴尬,而且公认抽象度差。或者,您可以为偏移量定义吸气剂(添加实例方法
xoffset
和yoffset
仅返回私有变量值)。然后您将拥有类似于cricket_007的解决方案的LEFT,UPPERLEFT,DOWN静态对象。在这种情况下,如果您想获取价值,可以致电grid[x + LEFT.xoffset()][y + LEFT.yoffset()]
设置
grid[x + LEFT.xoffset()][y + LEFT.yoffset()] = myValue;
根据定义,您不能自己实例化一个枚举。 Enums are initialized by the JVM,并且只有固定数目(在这种情况下为LEFT,UPPERLEFT,DOWN ...)。
关于java - 我可以使用“相对”变量创建HashMap吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38427058/