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

I think the final reference to the array of enumerations should be immutable.

The uniqueness and peculiarity of the enumerations is ensured by the JVM, so I believe that it is safe to say that they are immutable.

The final link cannot be changed, so the link is immutable.

But ... how about an array? Could it be possible to undermine an array containing enumeration references?

I have a list of enumerations matching the database columns. These column names and the data associated with them do not change, so ... I would like to have a list as a class variable like this:

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

where CLIENTS is a DataTable enumeration for which a list of column enumerations is created. 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())); } 

I'm right? This should become part of a multi-threaded design, and therefore I am concerned about how to make this critical list of static data application rendering very vulnerable ... if it is really modified.

+4
source share
3 answers

But ... how about an array? Could it be possible to undermine an array containing enumeration references?

Yes. All arrays in Java are mutable, regardless of how you declare a variable containing an array reference.

If you want to avoid this "risk", you should not expose the array; those. you need to declare it as private . Then you can do one (or more) of the following:

  • Define a static method that will create and return a copy of the array. (This is 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 ).

+11
source

If you want public <T extends DB> List<MetaData<T>> getTableColumnsAsEnums() return an immutable list, you need to use Collections.unmodifiableList()

Also, when you use an unmodifiable list, you do not need to worry about the internal array, because the toArray method returns a copy of the internal array, not a reference to the internal array. This is true for all Collections.

+4
source

The LINK is unchanged, the content of this link is not how everything works.
So the following will not work

 public enum TheEnum { //...... } final TheEnum[] arr = new TheEnum[5]; var = new TheEnum[6]; 

but it will work

 public enum TheEnum { OPTION_ONE; //...... } final TheEnum[] arr = new TheEnum[5]; var[1] = TheEnum.OPTION_ONE; 
+2
source

Source: https://habr.com/ru/post/1486741/


All Articles