您可以在 Cat 对象中添加一个静态方法,该方法将根据 Cat 的 ID 返回非静态变量。您需要在 Cat 对象内的静态地图中保留 Cats 列表。
private static HashMap<String,Cat> cats = new HashMap<String,Cat>();
...
public static int getEnergy(String catId) {
Cat myCat = cats.get(catId);
return myCat.getEnergy();
}
public int getEnergy() {
return this.energy()
}
或者根据要求,如果您想按 X、Y 搜索:
private static ArrayList<Cat> cats = new ArrayList<Cat>();
private int energy = 100;
private int x = 0;
private int y = 0;
...
public static int getEnergy(int x, int y) {
//Energy of -1 being the error (not found) state.
int energy = -1;
for(Cat cat : cats) {
if(cat.getX() == x && cat.getY() == y) {
energy = cat.getEnergy();
}
}
return energy;
}
public int getEnergy() {
return this.energy()
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}