2011-04-05 70 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 
    }