Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet47/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   43   44   45   46   47   48   49   50   ...   245
Bog'liq
Java 17 Recipes

 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 jvmLanguages = List.of("Java", "Scala", "JRuby", 
"Groovy", "Jython", "Kotlin");
System.out.println(jvmLanguages);
try {
jvmLanguages.add("Exception");
} catch (UnsupportedOperationException uoe){
System.out.println(uoe);
}
Map players = Map.of(1, "Josh Juneau", 2, 
"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, Set , and Map interfaces for 
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 factory method accepts ten key/value pairs. Furthermore, no null values can 
populate as elements, keys, or values.

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   43   44   45   46   47   48   49   50   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling