Java 常量数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33095100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 14:18:58  来源:igfitidea点击:

Java array of constants

javaarraysenums

提问by Athanasios V.

How is it possible to declare and initialize an array of constants in Java, without using enums?

如何在不使用的情况下在 Java 中声明和初始化常量数组enums

static final Type[] arrayOfConstants = new Type[10]; // not an array of constants

回答by Mustafa sabir

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

- 如果您事先知道这些值,请初始化数组值并将该数组标记为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)

- 如果您最初不知道这些值,则编写公共 getter/setter 方法并将数组声明为private. 在 setter 方法中编写逻辑以丢弃对特定元素所做的更改(或在对同一元素进行多次更改时引发异常)

回答by Tagir Valeev

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

如果你想创建一个不可变的数组,不,你不能。Java 中的所有数组都是可变的。

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_ARRAYof length 5, so MY_ARRAY[0]is 10and so on. Be careful though as even the MY_ARRAYfield 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 publicor protectedmodifier.

在这里,我们创建了一个预定义的阵列MY_ARRAY长度为5的,所以MY_ARRAY[0]10等等。请注意,即使MY_ARRAY字段被声明为 final,这并不意味着不能更改数组元素。因此,最好不要通过publicprotected修饰符将此类数组公开给公众。

回答by Vince Emigh

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

我的意思是数组组件是常量,即 a[0] 是一个像这样的常量变量 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. finalonly ensures you cannot re-assign the array variable, so you will want to encapsulate the array to prevent mutation:

请记住,尽管声明了一个数组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];
    }
}

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

如果您想循环,我建议返回数组的深层副本

回答by Atul Raj

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 与对象一起使用,您不能更改该对象的引用,但更改值是完全正确的。Array 是 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

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

有关不可变数组的更多信息,您可以参考以下链接:

Immutable array in Java

Java中的不可变数组

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

有没有办法在Java中使普通数组不可变?

回答by Florin Grigoriu

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

回答by NBaua

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 LanguageModelsimply contains two properties Id and Title or use whatever your model class of generic Type could be.

其中LanguageModel只包含两个属性 Id 和 Title 或使用您的泛型类型的任何模型类。

Should work great as constant.

应该像常数一样工作。

-- N Baua

-- N 鲍阿