Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
Solution
Utilize the Collection.of() construct to generate an immutable collection. In the following example, two collections are created. The first is an immutable List and the second is an immutable Map public static void main(String[] args){ List "Groovy", "Jython", "Kotlin"); System.out.println(jvmLanguages); try { jvmLanguages.add("Exception"); } catch (UnsupportedOperationException uoe){ System.out.println(uoe); } Map "Jonathan Gennick", 3, "Freddy Guime", 4, "Carl Dea", 5, "Luciano Manelli"); System.out.println(players.values()); System.out.println("Player 5: " + players.get(5)); try { players.put(6,"Exception"); } catch (UnsupportedOperationException uoe){ System.out.println(uoe); } } The output looks like the following. Note that the example includes a try-catch block to catch the UnsupportedOperationException thrown when there is an attempt to modify the list and the map. [Java, Scala, JRuby, Groovy, Jython, Kotlin] java.lang.UnsupportedOperationException [Josh Juneau, Jonathan Gennick, Freddy Guime, Carl Dea, Luciano Manelli] Player 5: Luciano Manelli java.lang.UnsupportedOperationException Chapter 2 enhanCements from Java 9 through Java 17 76 How It Works Java has historically been a verbose language for performing small tasks. In the past, constructing a populated collection of data took a few lines of code. On the first line, the collection must be initialized, followed by a line of code for each item that was added to it. Java adds the convenient API for quickly producing an unmodifiable collection of data, whereby one can now initialize and populate the construct in one line of code. Factory methods have been added to List creating such unmodifiable collections of data. The factory methods consist of the of() method, which accepts up to ten values, quickly creating an immutable collection. The Map populate as elements, keys, or values. Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling