Athanasios V.
Athanasios V.

Reputation: 319

Java array of constants

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

Upvotes: 11

Views: 68740

Answers (7)

baku9953
baku9953

Reputation: 13

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.

Upvotes: 0

NBaua
NBaua

Reputation: 684

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

Upvotes: 0

Florin Grigoriu
Florin Grigoriu

Reputation: 185

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);

Upvotes: 5

Atul Raj
Atul Raj

Reputation: 21

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?

Upvotes: 1

Vince
Vince

Reputation: 15146

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.

Upvotes: 3

Tagir Valeev
Tagir Valeev

Reputation: 100199

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.

Upvotes: 18

Mustafa sabir
Mustafa sabir

Reputation: 4360

-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)

Upvotes: 0

Related Questions