In Java, you can declare a list of objects as a constant by using the final
keyword and the Collections.unmodifiableList
method.
The final
keyword prevents the list from being reassigned to a different value. The Collections.unmodifiableList
method returns a view of the specified list that cannot be modified.
For example, consider the following code that declares a list of strings as a constant:
ot refer:lautturi.comimport java.util.Collections; import java.util.List; final List<String> list = Collections.unmodifiableList(Arrays.asList("apple", "banana", "cherry"));
This creates a constant list of strings with the elements "apple", "banana", and "cherry". The list cannot be modified, and any attempt to modify it will result in an UnsupportedOperationException
being thrown.
Note that the elements of the list are still mutable. For example, if the list contains objects of a class that has a mutable field, you can still modify the field through the list.
To make the elements of the list immutable as well, you can use an immutable class or an unmodifiable wrapper class. For example, you can use the Collections.unmodifiableMap
method to create an unmodifiable wrapper around a mutable map.
Here's an example of declaring a list of immutable objects as a constant:
import java.util.Collections; import java.util.List; import java.util.Map; final List<Map<String, String>> list = Collections.unmodifiableList(Arrays.asList( Collections.unmodifiableMap(new HashMap<>()), Collections.unmodifiableMap(new HashMap<>()), Collections.unmodifiableMap(new HashMap<>()) ));
This creates a constant list of unmodifiable maps. Any attempt to modify the list or the maps through the list will result in an UnsupportedOperationException
being thrown.