[英]Is there a more efficient way to reference an int array with a string than this
I have hundreds of small arrays each holding two ints representing an x, y coordinate on the screen.我有数百个小的 arrays 每个都有两个整数,代表屏幕上的 x,y 坐标。 The method passes in a string with the same name as the array holding its values.
该方法传入一个与保存其值的数组同名的字符串。 Rather than hard coding each case like this...
而不是像这样对每个案例进行硬编码......
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];
}
}
}
How can I do this more efficiently?我怎样才能更有效地做到这一点?
public static void main(String[] args) {公共 static 无效主(字符串 [] 参数){
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));
}
Instead of using array, you can use object as well.除了使用数组,您也可以使用 object。 I wonder if this helps.
我想知道这是否有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.