![](/img/trans.png)
[英]Is there a more efficient way to get formatted string than with Period/PeriodFormat?
[英]Is there a more efficient way to reference an int array with a string than this
我有數百個小的 arrays 每個都有兩個整數,代表屏幕上的 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];
}
}
}
我怎樣才能更有效地做到這一點?
公共 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));
}
除了使用數組,您也可以使用 object。 我想知道這是否有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.