Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java array of constants

Tags:

java

arrays

enums

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
like image 254
Athanasios V. Avatar asked Oct 13 '15 05:10

Athanasios V.


2 Answers

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.

like image 153
Tagir Valeev Avatar answered Nov 14 '22 07:11

Tagir Valeev


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);
like image 4
Florin Grigoriu Avatar answered Nov 14 '22 05:11

Florin Grigoriu