How is it possible to declare and initialize an array of constants in Java, without using enums
?
static final Type[] arrayOfConstants = new Type[10]; // not an array of constants
If you want to create an immutable array, no, you cannot. All arrays in Java are mutable.
If you just want to predefine the array in your class, you can do it:
private static final int[] MY_ARRAY = {10, 20, 30, 40, 50};
Here we created a predefined array MY_ARRAY
of length 5, so MY_ARRAY[0]
is 10
and so on. Be careful though as even the MY_ARRAY
field is declared final, this does not mean that array elements could not be changed. Thus it's better not to expose such array to public via public
or protected
modifier.
If you don't want to modify the values, and you also just want to access the members of the collection without wanting random access, a very simple solution instead of having a constant array, have a final immutable list:
static final ImmutableList<Type> arrayOfConstants = ImmutableList.of(t1, t2, t3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With