Java数组的常量
如何在不使用enums
情况下在Java中声明和初始化常量数组?
static final Type[] arrayOfConstants = new Type[10]; // not an array of constants
如果你想创建一个不可变数组,不,你不能。 Java中的所有数组都是可变的。
如果您只想在类中预定义数组,则可以执行以下操作:
private static final int[] MY_ARRAY = {10, 20, 30, 40, 50};
这里我们创建了一个长度为5的预定义数组MY_ARRAY
,因此MY_ARRAY[0]
为10
,依此类推。 但要小心,即使MY_ARRAY
字段被声明为final,这并不意味着无法更改数组元素。 因此,最好不要通过public
或protected
修饰符将此类数组公开给public。
我的意思是数组组件是常量,即a [0]是一个常量变量,如public static 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]; } }
如果你想循环,我建议返回数组的深层副本 。
如果你不想修改这些值,并且你只想访问集合的成员而不想随机访问,那么一个非常简单的解决方案而不是一个常量数组,有一个最终的不可变列表:
static final ImmutableList arrayOfConstants = ImmutableList.of(t1, t2, t3);
– 如果您事先知道了这些值,则初始化数组值并将该数组标记为final
。
– 如果您最初不知道这些值,则编写公共getter / setters方法并将该数组声明为private
。 在setter方法中编写逻辑,以便在对特定元素完成后丢弃更改(或在对同一元素进行多次更改时抛出exception)
如果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
有关不可变数组的更多信息,请参阅以下链接:
Java中的不可变数组
有没有办法让Java中的普通数组不可变?
它已经有一段时间了,这篇文章是开放的我很惊讶,为什么任何人都不会想到
public static final List GenderDataSource = new ArrayList(){{ add(new LanguageModel("0", "English")); add(new LanguageModel("1", "Hindi")); add(new LanguageModel("1", "Tamil")); };};
其中LanguageModel只包含两个属性Id和Title,或者使用genericsType的模型类。
应该不断努力。
– N Baua