Quantcast
Viewing latest article 12
Browse Latest Browse All 37

Answer by user85421 for Initialization of an ArrayList in one line

Java 9 has the following method to create an immutable list as documented (or documented as unmodifiableJava 10+):

List<String> places = List.of("Buenos Aires", "Córdoba", "La Plata");

which is easily adapted to create a mutable list, if required:

List<String> places = new ArrayList<>(List.of("Buenos Aires", "Córdoba", "La Plata"));

Similar methods are available for Set and Map.

Please note that these methods do not accept null elements, a little bit hidden in the documentation:

Throws:NullPointerException - if an element is null ...


Viewing latest article 12
Browse Latest Browse All 37

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>