Java 使具有位置括号的对象类似于阵列

Java 使具有位置括号的对象类似于阵列,java,arrays,object,Java,Arrays,Object,我试图创建一个有括号的对象,很像一个数组,但我希望它是一个对象,这样我就可以有hasLocation或returnMap等方法。我想要成为对象的数组称为Map。创建地图对象之前的代码如下: public class Main { public static void main(String[] args) { gamePreset(); } public static void gamePreset(){ /** * Creating Locations *

我试图创建一个有括号的对象,很像一个数组,但我希望它是一个对象,这样我就可以有hasLocation或returnMap等方法。我想要成为对象的数组称为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;
}
如果一切按我的方式进行,我的代码将如下所示:

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

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

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

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

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

Map newMap = new Map(2,2,"map00");
newMap.map[1][1] = location00;
只要做:

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

不。在Java中不可能。只有数组可以使用括号表示法。好的,那就必须用其他方法来完成。不。在Java中不可能。只有数组可以使用括号表示法。好的,那就必须用其他方法。这并不能回答问题。@Turing85为什么这不能回答他的问题?他要求一个更好的方法,而我的方法是有效的。这不能回答问题。@Turing85为什么这不能回答他的问题?他要求一个更好的方法,我的方法是有效的