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.

JavaScript

output:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement