[英]Java: How to return object when I have its name as a string?
假设我正在构建一个国际象棋游戏并创建棋盘空间对象。 我正在创建这样的对象,在国际象棋棋盘上的所有空间恰好是64个:
BoardSpace a1 = new BoardSpace("black", 1, 1, true);
这是我为BoardSpace对象创建的类:
public class BoardSpace {
String color;
int x_pos;
int y_pos;
boolean occupied;
//constructor
public BoardSpace (String color, int x_pos, int y_pos, boolean occupied) {
this.color = color;
this.x_pos = x_pos;
this.y_pos = y_pos;
this.occupied = occupied;
}
}
在棋盘上移动棋子之前,我先创建了所有的BoardSpace对象。 我的棋子对象每个都有一个x位置和y位置。 我想要做的是将其坐标转换为BoardPiece名称,然后从该名称中检索以前创建的BoardPiece对象。
这就是我想做的:
static String get_BoardSpace_color(int x_pos, int y_pos){
int modified_x = x_pos + 96; //adjusting for ASCII
char c = (char)(modified_x);
String space_name = ""+c+y_pos;
BoardSpace piece = (BoardSpace)(space_name); //PROBLEM AREA
return piece.color;
}
如何使用已经存在的对象名称的正确字符串表示形式来实际检索该对象?
同样, 对象没有名称。 是的,变量可以,但是变量的名称不是字符串,并且变量名称在编译后的代码中几乎不存在。 您需要的是一种对感兴趣的对象进行引用的方法,并且有多种方法可以做到这一点,包括:
Map<String, BoardSpace>
例如HashMap<String, BoardSpace>
。 这样,您可以将String与唯一对象相关联 ArrayList<BoardSpace>
类的集合,该集合使您可以通过int索引获取对象 BoardSpace[64]
List<List<BoardSpace>>
由于您似乎正在制作8×8的BoardSpace网格,并且由于这些尺寸可能不会改变,因此,最简单的方法是创建8x8的对象数组:
private BoardSpace[][] grid = new BoardSpace[8][8];
然后,您可以使用x和y(或行和列)索引来获取感兴趣的对象。
例如:
public class TestBoardSpace {
public static void main(String[] args) {
Board board = new Board();
for (int y = 0; y < Board.ROWS; y++) {
for (int x = 0; x < Board.COLS; x++) {
System.out.printf("%8s ", board.getBoardSpace(x, y).getColor());
}
System.out.println();
}
}
}
class Board {
public static final int ROWS = 8;
public static final int COLS = ROWS;
private BoardSpace[][] grid = new BoardSpace[ROWS][COLS];
public Board() {
for (int row = 0; row < grid.length; row++) {
for (int col = 0; col < grid[row].length; col++) {
MyColor color = row % 2 == col % 2 ? MyColor.BLACK : MyColor.WHITE;
grid[row][col] = new BoardSpace(color, col, row, false);
}
}
}
public BoardSpace getBoardSpace(int x, int y) {
// to get color, simply call getColor() on this
return grid[y][x];
}
}
// yes an enum here would be great and would protect against
// bad Strings
enum MyColor {
WHITE, BLACK
}
class BoardSpace {
private MyColor color;
private int x_pos;
private int y_pos;
private boolean occupied;
// constructor
public BoardSpace(MyColor color, int x_pos, int y_pos, boolean occupied) {
this.color = color;
this.x_pos = x_pos;
this.y_pos = y_pos;
this.occupied = occupied;
}
public boolean isOccupied() {
return occupied;
}
public void setOccupied(boolean occupied) {
this.occupied = occupied;
}
public MyColor getColor() {
return color;
}
public int getX_pos() {
return x_pos;
}
public int getY_pos() {
return y_pos;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.