0

i defined some final String arrays and initial them at another place, now i want to make it easier to traverse them, so maybe i need to put them in a final String[][] ,

  private static final String[] a,b,c,d;
  private static final String[][] all = {a,b,c,d};

but it give me errors

The blank final field a may not have been initialized

now i know the final variable should be assigned before used but i have no idea to solve my problem, is there any way to traverse a,b,c,d easier than the following code?

  for(String s : a){};
  for(String s : b){};
  ...

BTW i want to assign by traversing them

AngryYogurt
  • 755
  • 2
  • 7
  • 22

3 Answers3

2

As long as you know the size of a through d, you can initialize them when you declare them:

private static final String[] a = new String[YOUR_VALUE_HERE], 
                              b = new String[YOUR_VALUE_HERE],
                              c = new String[YOUR_VALUE_HERE],
                              d = new String[YOUR_VALUE_HERE];
private static final String[][] all = {a,b,c,d};

You can still initialize the contents of the arrays later, since only the array reference itself is final.

Brigham
  • 14,395
  • 3
  • 38
  • 48
0

If you want to have static and final arrays, I suggest you to use singleton patten with only accessors. That way you have one instance (static) and those arrays can't be changed on another (final).

public class ArrayContainer {
    private ArrayContainer instance = new ArrayContainer();
    private static final int SIZE_A = 1;
    private static final int SIZE_B = 2;
    private static final int SIZE_C = 3;
    private static final int SIZE_D = 4;
    private static String[] a, b, c, d;
    private static String[][] all;

    private ArrayContainer() {
        a = new String[SIZE_A];
        b = new String[SIZE_B];
        c = new String[SIZE_C];
        d = new String[SIZE_D];
        all = new String[][]{a, b, c, d};
    }

    public String[] getA(){
        return a;
    }

    public String[] getB(){
        return b;
    }

    public String[] getC(){
        return c;
    }

    public String[] getD(){
        return d;
    }

    public String[][] getAll(){
        return all;
    }
}

Anyway you should remember that final array is not immutable. If you would like to have immutable I suggest you read this: Immutable array in Java.

Still you can also add only getters like

public String get(int array, int index){
    return all[i][y];
}
Community
  • 1
  • 1
KonradOliwer
  • 166
  • 6
0

If you need to init your static fields, use static block:

static final String[] a;
static {
    // put all the logic here
    // and assign final var at the end
    a = new String[17];
}
static final String[][] all = {a};

Remember also, that order in example above is important. Declaration of all array before initialization of a would cause The blank final field a may not have been initialized error.

Artur Malinowski
  • 1,124
  • 10
  • 30