有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

数组可能是Java For循环问题

好的,我正在将大约120个特定数组的列表添加到数组列表中 (这些只是假设值和名称,但概念相同

private ArrayList<int[]> listofNames = new ArrayList<int[]>();

private static int[] NAME_0 = {x, x, x};

private static int[] NAME_1 = {x, x, x};

private static int[] NAME_2 = {x, x, x};

private static int[] NAME_3 = {x, x, x};

有没有一种方法可以使用for循环通过NAME_0来表示NAME_120


共 (4) 个答案

  1. # 1 楼答案

    你可以使用反射,但你几乎肯定不应该使用反射

    您通常应该使用数组数组,而不是使用末尾带有数字的变量。毕竟,这就是阵列的用途

    private static int[][] NAMES = new int[][]{
        {x, x, x},
        {x, x, x},
        {x, x, x},
        {x, x, x},
        {x, x, x},
        /// etc.
      };
    

    如果您只是将这些内容添加到ArrayList中,您可能只需使用初始值设定项块即可:

    private ArrayList<int[]> listofNames = new ArrayList<int[]>();
    
    {
      listofNames.add(new int[]{x, x, x});
      listofNames.add(new int[]{x, x, x});
      listofNames.add(new int[]{x, x, x});
      /// etc.
    }
    
  2. # 2 楼答案

    正如劳伦斯所建议的,你可以使用反射

        for(int i=0; i<=120; i++)
        {
    
            Field f = getClass().getField("NAME_" + i);
            f.setAccessible(true);
            listofNames.add((int[]) f.get(null));
        }
    

    正如劳伦斯所建议的,有更好的方法来做到这一点

  3. # 3 楼答案

    IRL很少用于数组(或者本质上不可能是线程安全的可变数据包)。例如,您可以使用如下函数:

    public static <T> ArrayList<T> L(T... items) {
        ArrayList<T> result = new ArrayList<T>(items.length + 2);
        for (int i = 0; i < items.length; i++)
            result.add(items[i]);
        return result;
    }
    

    因此,创建一个列表并循环它看起来:

        ArrayList<ArrayList<Field>> list = L(//
                L(x, x, x), //
                L(x, x, x), //
                L(x, x, x), //
                L(x, x, x) // etc.
        );
    
        for (int i = 0; i < list.length || 1 < 120; i++) {
    
        }
    
        //or
        int i = 0;
        for (ArrayList<Field> elem: list) {
            if (i++ >= 120) break;
            // do else
        }
    
  4. # 4 楼答案

    如果你真的想用提问的方式去做,你必须使用反思。大概是这样的:

    Class cls = getClass();
    Field fieldlist[] = cls.getDeclaredFields();        
    for (Field f : fieldlist) {
        if (f.getName().startsWith("NAME_")) {
            listofNames.add((int[]) f.get(this));
        }
    }