Skip to content
Advertisement

Expose `final static Set` of a class

I have a class that has:
public static final Set<String> IDS = new HashSet<>();,
whose values are initiated in a static block after running some query (Therefore I can’t declare it as unmodifiableSet).

Now that other classes need to use IDS but apparently I don’t want to let them get direct access to it to avoid IDS being changed by callers.
To achieve this, one way I can think of, is to

  1. make IDS private
  2. create a getter method that will return new HashSet<>(IDS) (or ImmutableSet as I’m using Guava)

But wondering if there are better ways?

Advertisement

Answer

Try this.

public static final Set<String> IDS;
static {
    Set<String> set = new HashSet<>();
    set.add("a");
    set.add("b");
    set.add("c");
    IDS = Collections.unmodifiableSet(set);
}


public static void main(String[] args) {
    System.out.println(IDS);
    IDS.add("x");
}

output:

[a, b, c]
Exception in thread "main" java.lang.UnsupportedOperationException
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement