shoconinja
shoconinja

Reputation: 195

Possible Java For Loop Question

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, 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?

Upvotes: 1

Views: 223

Answers (4)

Margus
Margus

Reputation: 20068

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
    }

Upvotes: 0

lukastymo
lukastymo

Reputation: 26809

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

Upvotes: 1

Bala R
Bala R

Reputation: 109037

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.

Upvotes: 1

Laurence Gonsalves
Laurence Gonsalves

Reputation: 143314

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

Upvotes: 12

Related Questions