Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: is a final reference to an array of enums immutable?

I think that a final reference to an array of enums should be immutable.

The uniqueness and singularity of enums is enforced by the JVM, so I believe it is safe to say that they are immutable.

A final reference cannot be changed, so the reference is immutable.

But ... what about the array? Might it still be possible to subvert the array that contains the enum references?

I have a list of enums that correspond to database columns. These column names and their associated data do not change, so ... I would like to have the list as a class variable like so:

static final List<MetaData<Client>> C_COLUMNS =
        DataTables.CLIENTS.getTableColumnsAsEnums();

where CLIENTS is the DataTable enum for which a list of column enums is being generated. The method that does this follows:

public <T extends DB> List<MetaData<T>> getTableColumnsAsEnums() {
    Class<? extends MetaData> cls = this.columnsEnumToken();
    return new ArrayList(Arrays.<MetaData<T>>asList(cls.getEnumConstants())); }

Am I right? This ought to become part of a multi-threaded design, and so I am concerned about the way that making this critical list of static data would render by app very vulnerable ... if it actually were mutable.

like image 432
scottb Avatar asked Dec 03 '22 22:12

scottb


1 Answers

But ... what about the array? Might it still be possible to subvert the array that contains the enum references?

Yes. All arrays in Java are mutable, irrespective of how you declare the variable that holds the reference to the array.

If you want to avoid this "risk", then you must not expose the array; i.e. you need to declare it as private. You could then do one (or more) of the following:

  • Define a static method that will create and return a copy of the array. (Probably not the best option here ...)

  • Define a static get(int) method that returns the ith element of the array.

  • Wrap the array in a list (using Arrays.asList) and create an unmodifiable wrapper for it (using Collections.unmodifiableList).

like image 105
Stephen C Avatar answered Dec 25 '22 15:12

Stephen C