I would like to have a constant set in my class that will be visible to all instances of the class.
Firstly, I don’t know if it should be declared as “static”. As far as I understand, any changes to the static field (made by one of the instances) will be considered by other instances (therefore, the static variable is not tied to a specific instance). Moreover, the static field can be changed without using any instance (we work directly with the class). Thus, all these special properties of a static field are related to how it can be changed and what are the consequences of these changes. But in my case, I would like to have a constant (therefore, problems with "changes" are not relevant here). Therefore, probably I do not need to use "static". Correctly?
Secondly, my set will contain many elements, and I do not want to immediately determine the value of the set (when I create a variable). In other words, I would like to declare a set, and then add the elements to this set step by step. But I can not do this if I work with constants. Is it possible to set a given value and then make it permanent?
Thirdly, I realized that some problems might arise if I try to change the value of variables outside of any method. So how does it work?
ADDED:
OK Thanks to the answer, I realized that it should be “final” and “static” (since it is constant and it will not be associated with any particular instance, it should be visible to all instances of the class). However, I still have a problem. I wanted to specify a set using "add", and I cannot add to a set if it is permanent. Moreover, I cannot change the values of variables outside of methods (why?). Anyway, I do not insist on using "add" to define the set. I am ready to immediately identify it. But I do not know how to do this. I tried things like this:
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 someone explain to me the requests, the code given by Tadeusz Kopek?
class YourClass {
private static void fillSet(Set<SomeType> set) {
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. fillSet , "set". ?
2. SomeType() fillSet? ?
3. fillSet? . ?
4. tempSet ?
5. unmodifiableSet ? , , . , yourSetField final? .