Search code examples
javastaticruntimesetfinal

Add (or remove) objects to a final static HashSet at runtime in Java?


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


Solution

  • The reference to your name variable is basically a constant and cannot be modified. However, the content of the set can be mutated during runtime as you discovered. To prevent that, you can make it immutable, e.g.

    final private static Set name = Collections.unmodifiableSet(new HashSet(){
        {
            add(object1); 
            ...; 
            add(objectN);
        }
    });