开发者

Possible Java For Loop Question

开发者 https://www.devze.com 2023-02-22 02:32 出处:网络
Ok so i\'m working on adding a list of about 120 or so specific arrays into an array list (These are just hypothetical values and names, but the same concept

Ok so i'm working on adding a list of about 120 or so specific arrays into an array list (These are just hypothetical values and names, but the same concept

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, 开发者_StackOverflow社区x, x};

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

Is there a way I can use a for loop to get through NAME_0 to say NAME_120?


You could use reflection, but you almost certainly shouldn't.

Instead of using variables with numbers at the end you should generally use an array of arrays instead. This is what arrays are for, after all.

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

If you're just adding these all to an ArrayList you can probably just use an initializer block instead:

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


You could do, as Laurence suggested, using reflection

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

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

Also as suggested by Laurence, there are better way to do this.


If you want really do in the way from your question you'll have to use reflection. Something like this:

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


IRL there is little, use for arrays (or mutable bags of data, that in nature, can not be thread safe). For example you could have a function like:

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

So creating a list, and looping it would look:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号