Java array of constants

How can I declare and initialize an array of constants in Java without using enums?

static final Type[] arrayOfConstants = new Type[10]; // not an array of constants
+4
source share
6 answers

If you want to create an immutable array, no, you cannot. All arrays in Java are mutable.

If you just want to predefine an array in your class, you can do this:

private static final int[] MY_ARRAY = {10, 20, 30, 40, 50};

MY_ARRAY 5, MY_ARRAY[0] - 10 . , MY_ARRAY , , . , public protected.

+5

, , .. [0] - , public public final int SIZE = 10;

.

, :

public static final int SIZE = 10;

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

, final, . final , , :

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

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

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

, .

+2

, , , :

static final ImmutableList<Type> arrayOfConstants = ImmutableList.of(t1, t2, t3);
+1

- before-hand, final.

- , getter/seters private. setter, ( )

0

final , , . Aray - java, , , 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

:

Java

Java?

0
source

This post is open from time to time. I am surprised why no one thought about

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 everything that might be in your generic Type model class.

Should work as a permanent.

- N Baua

0
source

Source: https://habr.com/ru/post/1611372/


All Articles