the*_*ers 1 java arrays loops for-loop arraylist
好的,我正在努力将大约120个左右的特定数组列表添加到数组列表中(这些只是假设的值和名称,但是相同的概念
private ArrayList<int[]> listofNames = new ArrayList<int[]>();
private static int[] NAME_0 = {x, x, x};
Run Code Online (Sandbox Code Playgroud)
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?
Lau*_*ves 12
你可以使用反射,但你几乎肯定不应该.
最后,您应该使用数组数组,而不是在末尾使用带数字的变量.毕竟,这就是阵列的用途.
private static int[][] NAMES = new int[][]{
{x, x, x},
{x, x, x},
{x, x, x},
{x, x, x},
{x, x, x},
/// etc.
};
Run Code Online (Sandbox Code Playgroud)
如果您只是将这些全部添加到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.
}
Run Code Online (Sandbox Code Playgroud)