Reputation: 7691
How to declare an array in which all the values (or objects) are constant in java.
For eg: say a[0] is a constant, a[1] is a constant,etc....
Upvotes: 0
Views: 1724
Reputation: 1
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. 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)
I would still say, Enum is the best way to store constants. However, the above implementation may be helpful below JDK5. Hope that helps!!!
Upvotes: 0
Reputation: 787
you use the keyword final
for declaring constant in java
for eg. final Stirng sr="hello";
Upvotes: 0
Reputation: 114817
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). 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.)
Upvotes: 3
Reputation: 1503090
Do you mean you don't want the array to be modifiable? You can't. Java doesn't support the C++-style "const" concept. 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 (i.e. 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.
Upvotes: 4
Reputation: 5192
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
Upvotes: 7