【问题标题】:Possible Java For Loop Question可能的 Java For 循环问题
【发布时间】:2011-07-30 09:12:29
【问题描述】:

好的,我正在努力将大约 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?

【问题讨论】:

    标签: java arrays loops for-loop arraylist


    【解决方案1】:

    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
        }
    

    【讨论】:

      【解决方案2】:

      如果你真的想从你的问题中解决问题,你将不得不使用反射。像这样的:

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

      【讨论】:

        【解决方案3】:

        您可以按照 Laurence 的建议使用反射

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

        正如 Laurence 所建议的,还有更好的方法来做到这一点。

        【讨论】:

          【解决方案4】:

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

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

          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.
          }
          

          【讨论】:

          • 非常感谢,比添加到arrayList简单多了
          • @Ben 使用泛型也不太麻烦。数组和泛型并不是很喜欢对方,所以最好不要混合使用。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2013-07-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多