2011-04-05 72 views
1

好了,所以我在努力增加约120个左右的特定阵列的列表到一个数组列表 (这只是假设值和名称,但相同的概念可能的Java For循环问题

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?

回答

12

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

而不是在最后使用带数字的变量,而应该使用数组数组。毕竟,这就是数组的用处。

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

非常感谢您,简单得多比添加到一个ArrayList – 2011-04-05 22:38:42

+1

@Ben也少仿制药麻烦。数组和泛型不太喜欢对方,所以最好不要混合它们。 – 2011-04-05 22:42:23

1

你可以做,如劳伦斯建议,使用反射

for(int i=0; i<=120; i++) 
    { 

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

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

1

如果你真的想从你的问题的方式做,你将不得不使用反射。事情是这样的:

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

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 
    }