I would like to have a constant set in my class which would be visible for all instances of the class.
First, I do not know if I need to declare it as "static". As far as I understand any changes of a static field (done by one of the instances) will be seen by other instances (so static variable is not bound to a specific instance). Moreover, a static field can be changes without usage of any instance (we work directly with the class). So, all these special properties of the static field are related with the way how it can be changed and what be the effect of these changes. But in my case I would like to have a constant (so the "changes" issues are not relevant here). So, probably I do not need to use "static". Right?
Second, my set will contain a lot of elements and I do not want to define the value of the set at once (when I create the variable). In other words I would like to declare a set, then add elements to this set step by step. But I cannot do it if I work with constants. Is it possible to specified value of the set and then make it constant?
Third, I have realized that there can be some problems if I try to change value of variables outside of any method. So, how does it work?
ADDED:
OK. Thanks to the answer I understood that it should be "final" and "static" (since it is a constant set and it will not be associated with any particular instance, it just should be visible to all instances of the class). However I still have a problem. I wanted to specify the set using "add" and I cannot add to the set if it is constant (final). Moreover, I cannot change values of the variables outside methods (why?). Anyway, I do not insist on the usage of "add" to define the set. I am ready to define it at once. But I do not know how to do it. I tried things like that:
final static Set allowedParameters = new HashSet("aaa","bbb");
final static Set allowedParameters = new HashSet(["aaa","bbb"]);
final static Set allowedParameters = new HashSet({"aaa","bbb"});
final static Set allowedParameters = new HashSet(Arrays.asList({"userName"}));
And they did not work.
ADDED 2:
Can anybody explain me, pleas, the code given by Tadeusz Kopec?
class YourClass {
private static void fillSet(Set<SomeType> set) {
// here you add elements, like
set.add(new SomeType());
}
private final static Set<SomeType> yourSetField;
static {
final Set<SomeType> tempSet = new HashSet<SomeType>();
fillSet(tempSet);
yourSetField = Collection.unmodifiableSet(tempSet);
}
}
1. The fillSet
method has one variable called "set". Why it is not used in the method?
2. What is SomeType()
in the fillSet
? What does this method do?
3. What does fillSet
do? Later in the example we give an empty set to this method. What for?
4. What for do we declare tempSet
as final?
5. What exactly unmodifiableSet
do? According to the name it generate a set which cannot be modified, I think. But why would it be insufficient to declare yourSetField
as final
? Than it would be constant too.