首页 > 解决方案 > 使用类似于数组的位置括号制作对象

问题描述

我正在尝试创建一个带有括号的对象,就像一个数组,但我希望它是一个对象,以便我可以拥有诸如hasLocationreturnMap 之类的方法。我想成为对象的数组称为 Map。我创建 Map 对象之前的代码如下:

public class Main {
public static void main(String[] args) {
    gamePreset();
}
public static void gamePreset(){
    /**
     * Creating Locations
     * It is important to note that the yPos starts in the left corner of the map and increases southward.
     * (0,0)|(1,0)|(2,0)
     * -----------------
     * (0,1)|(1,1)|(2,1)
     * -----------------
     * (0,2)|(1,2)|(2,2)
     */
    Location location00 = new Location(0,0,entities00,"This is location 00. Welcome to the map.");
    Location location01 = new Location(0,1,entities01,"This is location 01. You are south of location 00.");
    Location location11 = new Location(1,1,entities01,"This is location 11. You are southeast of location 00.");
    Location location10 = new Location(1,0,entities01,"This is location 10. You are east of location 00.");

    //Adding Locations to the Map Array
    Location[][] map = new Location[2][2];
    map[0][0] = location00;
    map[0][1] = location01;
    map[1][1] = location11;
    map[1][0] = location10;

    System.out.println(returnMap(map));
}

public static String returnMap(Location[][] map){
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < map.length; i++){
            for(int j = 0; j < map[i].length; j++){
                sb.append("(" + map[i][j].getXPos() + "," + map[i][j].getYPos() + ")");
                sb.append(" ");
            }
            sb.append("\n");
        }
        return sb.toString();
    }

public static boolean hasLocation(Location[][] map, int xPos, int yPos){
    if(map[xPos][yPos]!=null){
        return true;
    }
    return false;
}

Location 包含一个 xPosition、一个 yPosition、一条消息和该位置的对象列表。我想要的是一个仍然像我的数组一样具有括号位置的对象: Location[][] map = new Location[2][2]; 这可能吗?有没有更好的方法来解决它?我试图创建一个构造函数,但我不确定如何进行:

public class Map {
    public Location[][] map;
    Map(int xHeight, int yHeight, String mapName){
        Location[][] mapName = new Location[xHeight][yHeight];
    }
    .....methods like returnMap.....
}

如果一切按我的方式进行,我的代码将如下所示:

Map newMap = new Map(2,2,"map00");
newMap[1][1] = location00;

标签: javaarraysobject

解决方案


只需在 Map 类中声明一个新函数?像这样的东西呢:

public void setLocation(int x, int y, Location loc){
    this.map[x][y] = loc;
}

推荐阅读