简体   繁体   English

Java中的常数

[英]Constants in Java

How to declare an array in which all the values (or objects) are constant in java. 在Java中,如何声明一个数组,其中所有值(或对象)都是常量。

For eg: say a[0] is a constant, a[1] is a constant,etc.... 例如:说a [0]是常数,a [1]是常数,等等。

How about using an Enum? 如何使用枚举?

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY, 
    THURSDAY, FRIDAY, SATURDAY 
}

http://download.oracle.com/javase/tutorial/java/javaOO/enum.html http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

Do you mean you don't want the array to be modifiable? 您是说不希望数组可修改吗? You can't. 你不能 Java doesn't support the C++-style "const" concept. Java不支持C ++风格的“ const”概念。 You'd have to use a read-only collection of some kind. 您必须使用某种只读集合。 Likewise you can't declare that the elements of the array should only be used in a read-only fashion (ie not mutated themselves, which is different from mutating the array to change the elements within it). 同样,你不能声明该阵列的元件应该只在只读方式使用 (即不突变本身,这是从突变的阵列,以改变在其内的元件的不同)。

If you give us more information about what you're trying to do, we may be able to suggest an alternative approach. 如果您向我们提供有关您要做什么的更多信息,我们也许可以建议另一种方法。

You can declare the entire array as a constant, but not the content of that array. 您可以将整个数组声明为常量,但不能声明该数组的内容。

A solution to you problem: use an unmodifiable List instead of an array (if possible). 解决您的问题的方法:使用不可修改的List而不是数组(如果可能)。 This gurantees that the stored values can't be "replaced". 这保证了不能“替换”存储的值。

(which means: if you store objects you'll still be able to change the properties of those objects, but you can't add, delete or replace the objects itselves.) (这意味着:如果存储对象,您仍然可以更改那些对象的属性,但不能自行添加,删除或替换对象。)

I suppose there is a decent way we can achieve this. 我想我们有一个不错的方法可以实现这一目标。 What I would suggest is create a class with private final array and provide a public method to read any of the element of the array. 我建议创建一个带有私有final数组的类,并提供一个公共方法来读取数组的任何元素。 This way you would be able to restrain the users from modifying your values because you are only setting a getter without providing a setter. 这样,您将能够限制用户修改您的值,因为您只设置了吸气剂而没有提供设置器。 Hope that helps!!! 希望有帮助!!!

class Constants{ 常量类{

private Constants(){
    throw new AssertionError("This class is not meant for instantiation");
}

private static final int[] myConstants = {3, 5, 8, 9, 23};

public static int getMyConstant(int i){
    return myConstants[i];
}

} }

Use the constants like Constants.getMyConstant(index) 使用类似Constants.getMyConstant(index)的常量

I would still say, Enum is the best way to store constants. 我仍然会说,枚举是存储常量的最佳方法。 However, the above implementation may be helpful below JDK5. 但是,在JDK5以下,上述实现可能会有所帮助。 Hope that helps!!! 希望有帮助!!!

you use the keyword final for declaring constant in java 您使用关键字final在Java中声明常量

for eg. 例如 final Stirng sr="hello";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM