java - 有没有比这更有效的方法来引用带有字符串的 int 数组
问题描述
我有数百个小数组,每个数组都有两个整数,代表屏幕上的 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];
}
}
}
我怎样才能更有效地做到这一点?
解决方案
公共静态无效主要(字符串[]参数){
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));
}
除了使用数组,您也可以使用对象。我想知道这是否有帮助。