简体   繁体   English

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

[英]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.

相关问题 有没有比使用Period / PeriodFormat更有效的方式来获取格式化的字符串? - Is there a more efficient way to get formatted string than with Period/PeriodFormat? 比这更有效的方式拆分? - More efficient way splitting than this? 如果1个int []数组中的所有值都小于或等于另一个int []数组,是否有一种优雅的方法(简短高效)进行比较? - Is there an elegant way (short and efficient) to compare if all the values in 1 int[] array are lesser than or equals to another int[] array? 是否有更有效的方法来更新列表视图或循环遍历字符串数组 - Is there a more efficient way to update the listview or loop through a string array 更有效的拆分字符串的方法 - more efficient way to split string 是否有更有效的方法添加到数组? - Is there a more efficient way to add to an Array? 在检查平等时将字符串转换为Int或Int转换为字符串是否更高效? - Is it More Efficient to Convert String to Int or Int to String When Checking for Equality? 将 int 转换为 String 的最有效方法是什么? - What is the most efficient way to convert an int to a String? 计算int数组中唯一对的有效方法 - Efficient way to count unique pairs in int array 有没有更有效的方法来计算带有树状图的字符串的实例? - Is there a more efficient way of counting instances of a string with treemaps?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM