Add (or remove) objects to a final static HashSet at runtime in Java?-Collection of common programming errors
I’m working with Java 4; some time ago I came across a variable which was declared in a public class as:
final private static Set name = new HashSet(){
{
add(object1);
...;
add(objectN);
}
};
and I needed to add (or remove) objects to it at runtime under some circumstances.
The class had a public constructor which was called before I had to either add or remove objects to said Set.
I thought that final variables were treated as constants so I wouldn’t be able to call the .add(object) and .remove(object) methods on it at runtime. But I did it anyway, I created two public methods to perform the add and remove operations, and it worked.
Why? I’d expected it either not to compile or to throw some kind of exception at runtime.
Can someone explain?
Thank you very much,
best regards