还有比此方法更有效的方法来引用带有字符串的int数组

问题描述 投票:0回答:1

我有数百个小的数组,每个数组都包含两个表示屏幕上x,y坐标的整数。该方法传入与保存其值的数组同名的字符串。而不是像这样硬编码每种情况...

public class Main {

    int[] a = {1000, 500},
          b = {900, 400},
          c = {800, 300};

    public method(String tile) {
        int x = 0, y = 0;

        switch(tile) {
        case "a": x = a[0]; y = a[1];
        case "b": x = b[0]; y = b[1]; 
        case "c": x = c[0]; y = c[1];
        }
    }       
}

如何更有效地执行此操作?

java arrays string variables names
1个回答
0
投票

public static void main(String [] args){

    int[] a = {1000, 500};
    int[] b = {900, 400};
    int[] c = {800, 300};

    Map<String, int[]> stringToTile = new HashMap<>();
    stringToTile.put("a", a);
    stringToTile.put("b", b);
    stringToTile.put("c", c);

    testMethod("a", stringToTile);
    testMethod("b", stringToTile);
    testMethod("c", stringToTile);
}

public static void testMethod(String tile, Map<String, int[]> stringToTile) {
    int[] resultArray = stringToTile.get(tile);
    int x = 0, y = 0;
    if (resultArray != null) {
        x = resultArray[0];
        y = resultArray[1];
    }
    System.out.println(String.format("x: %s; y: %s", x, y));
}

除了使用数组之外,还可以使用对象。我想知道这是否有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.