简体   繁体   中英

Initialize static final array with indexes

I want to initialize a multidimensional private static final array of ints, indexing the values.

private static final int[][] a = { {0,0,0}, {1,2,3} };

This is NOT good for me. I found somewhere this weird syntax that I tried, but does not want to compile in anyway. I add it to clarify what I need:

private static final int[][] a;
private static {
    a = new int[NUM_TYPES][3];
    a [TYPE_EMPTY]  =   { 0, 0, 0 };
    a [TYPE_NORMAL] =   { 1, 2, 3 };
    };

The difference is that now I should have a[TYPE_EMPTY] and a[TYPE_NORMAL] instead of a[0] and a[1]. On the practical side it's the same, but the second one makes much more clear, error-free and maintainable the source.

For example, should I add a new TYPE in future, I would not need to care what numerical index would have inside the array.

As I said, I did not find any correct syntax to do that, and the above syntax is completely wrong. Would some Java expert give me a short lesson? :) Thank you very much.

Try this -

private static final int[][] a;
private static final int NUM_TYPES  = 2;
private static final int TYPE_EMPTY = 0;
private static final int TYPE_NORMAL = 1;

static { // static initializer  block.
    a = new int[NUM_TYPES][3];
    a [TYPE_EMPTY] =  new int[]{ 0, 0, 0 };
    a [TYPE_NORMAL] = new int[]{ 1, 2, 3 };
}

Reference on Static initilizing block

I would suggest to use enums to hold your data:

public enum TYPE {
  TYPE_EMPTY(0,0,0),
  TYPE_NORMAL(1,2,3);

  private int[] data; 

  TYPE(int... data) {
     this.data = data;
  }

  public int[] getData() {
     return data;
  }
}

You can get an array of all enum instances by using TYPE.values() .

Reasoning: I think if you have already names for your data rows, they actually mean something for you, so they deserve to be real objects. If you have a small set of "constant" instances, then enums are a good choice. This design gives you much more flexibility (you can make a defensive copy of the data array, add new attributes, you can add, rearrange or remove enum instances etc without breaking anything).

Whenever I see private static final int ... defining hard offsets etc. I try to think of a way of using enums to solve the problem because - after all - that is what they are.

I came up with this:

enum MyType {
  Empty(null),
  Normal(new int[] {1,2,3});
  // My values.
  final int [] values;
  // Constructor.
  MyType(int [] values) {
    this.values = values;
  }

  // Getter - equivalent to the array access.
  public int get(int i) {
    return values == null ? 0 : values[i];
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM