Java数组的常量 [英] Java array of constants

查看:390
本文介绍了Java数组的常量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

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

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

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

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.

这篇关于Java数组的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆