11

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
Athanasios V.
  • 319
  • 1
  • 4
  • 14
  • 5
    You mean ensure the values of the array cannot be changed? You will need to encapsulate the array in an object that prevents mutation but allows access by index via getter method – Vince Oct 13 '15 at 05:55
  • I mean the array components be constants i.e. a[0] be a constant variable like this public static final int SIZE = 10; – Athanasios V. Oct 13 '15 at 05:58
  • 2
    I'm not sure what you mean. You want to give the array indexes names? – Vince Oct 13 '15 at 05:59
  • @Vince Emigh Your answer before makes sense to me. – Athanasios V. Oct 13 '15 at 06:08
  • What answer? The only answer I have is [down below](http://stackoverflow.com/a/33095247/2398375), which you can kindly choose as accepted answer if it helped with your issue :) Unless you're referring to my comment, which in that case my answer includes that info (with examples), and you should check it out – Vince Oct 13 '15 at 06:17
  • I think there are Immutable Collections in java, but not arrays unfortunately – niceman May 28 '16 at 15:34

7 Answers7

18

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
4

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);
Florin Grigoriu
  • 169
  • 1
  • 3
3

I mean the array components be constants i.e. a[0] be a constant variable like this public static final int SIZE = 10;

You cannot give array indexes names.

You could initialize an array using the values of pre-existing constants:

public static final int SIZE = 10;

public static final int[] CONSTANTS = { SIZE };

Keep in mind that although an array is declared final, it's values may still be changed. final only ensures you cannot re-assign the array variable, so you will want to encapsulate the array to prevent mutation:

final class Constants {
    public static final int SIZE = 10;

    private static final int[] CONSTANTS = { SIZE };

    public static int getConstant(int index) {
       return CONSTANTS[index];
    }
}

If you would like to loop, I suggest returning a deep-copy of the array.

Vince
  • 14,470
  • 7
  • 39
  • 84
  • 1
    The question wasn't "how do I give array indices names", it was "how do I make an array of constants, this thing shows what I mean by constant". Your answer says "you can't do this unrelated thing, oh and by the way you should keep in mind this caveat which is literally the entire center of your question". – Nic Nov 29 '18 at 04:11
1

if final is used with objects you cannot change the reference of that object but changing the value is perfectly fine.Array is an object in java and if you want object value should not be changed, once created, then you will have to make object immutable and primitive array cannot be made immutable in java.

    final int [] finalArr={5,6,8};

     System.out.println("Value at index 0 is "+finalArr[0]);    
      //output : Value at index 0 is 5

      //perfectly fine
      finalArr[0]=41;

     System.out.println("Changed value at index 0 is "+finalArr[0]);
    //Changed value at index 0 is 41

     int[] anotherArr={7,9,6};
     // finalArr=anotherArr;
     //error : cannot assign a value to final variable finalArr

For more on immutable array you can refer to these links:

Immutable array in Java

Is there any way to make an ordinary array immutable in Java?

Community
  • 1
  • 1
Atul Raj
  • 21
  • 2
0

-If you know the values before-hand, initialize the array values and mark that array as final.

-If you don't know the values initially then write public getter/setters methods and declare the array as private. Write logic in setter method to discard changes once done on a particular element (or throw an exception upon multiple changes to the same element)

Mustafa sabir
  • 4,130
  • 1
  • 19
  • 28
0

Its'been a while this post is open I am surprised, why any one would not think of

public static final List<LanguageModel> GenderDataSource = new ArrayList<GenderModel>(){{
    add(new LanguageModel("0", "English"));
    add(new LanguageModel("1", "Hindi"));
    add(new LanguageModel("1", "Tamil"));
};};

Where LanguageModel simply contains two properties Id and Title or use whatever your model class of generic Type could be.

Should work great as constant.

-- N Baua

NBaua
  • 583
  • 4
  • 16
  • 33
0

I saw this post and it made me think about something I did for a chess playing application.

Maybe you just want a group of constants that are sons of another constant. I mean, if you make a final class named as your "array", and inside it you describe several constants, you'll be able to access it via MyClass.MYARRAY.MYCONSTANT.

The code would be:

abstract class Figure {
    public static final class WEIGHT{
        public static final int PAWN = 1;
        public static final int KNIGHT = 3;
        public static final int BISHOP = 3;
        public static final int ROCK = 5;
        public static final int QUEEN = 10;
        public static final int KING = 1000;
    }
}

public class Pawn extends Figure{
    public static final int weight = Figure.WEIGHT.PAWN;
}

I don't know if it is the best way for doing it. I don't either know if it's the worst way. But I think it answers your question and gives you a solution.

albert_bk
  • 1
  • 3