UnmodifiableMap () en las colecciones de Java se usa para obtener la vista no modificable para el mapa dado.
Sintaxis:
public static <Key,Value> Map<Key,Value> unmodifiableMap(Map<? extends Key, ? extends Key> map)
Parámetros:
- Clave es el tipo clave-valor
- El valor es el tipo de valor
- map es el mapa de entrada
Devolver: Devolverá la vista no modificable para el mapa dado.
Excepciones: Este método no arrojará ningún tipo de excepción.
Ejemplo 1:
Java
// Java program to create a map with // string values and get the // unmodifiable view import java.util.*; public class GFG { // main method public static void main(String[] args) { // create hashmap HashMap<String, String> data = new HashMap<String, String>(); // add elements to the created hashmap data.put("1", "manoj"); data.put("2", "sai"); data.put("3", "ramya"); data.put("4", "sravan"); // display the data System.out.println(data); // Create unmodifiable map for the above map Map<String, String> final1 = Collections.unmodifiableMap(data); // display unmodifiable map System.out.println(final1); } }
Producción
{1=manoj, 2=sai, 3=ramya, 4=sravan} {1=manoj, 2=sai, 3=ramya, 4=sravan}
Ejemplo 2:
Java
// Java program to create a map // with integer values and get // the unmodifiable view import java.util.*; public class GFG { // main method public static void main(String[] args) { // create hashmap HashMap<Integer, Integer> data = new HashMap<Integer, Integer>(); // add elements to the created hashmap data.put(1, 67); data.put(2, 34); // display the data System.out.println(data); // Create unmodifiable map for the above map Map<Integer, Integer> final1 = Collections.unmodifiableMap(data); // display unmodifiable map System.out.println(final1); } }
Producción
{1=67, 2=34} {1=67, 2=34}
Ejemplo 3: Tirará un error cuando añadimos un elemento a un mapa modificable.
Java
import java.util.*; public class GFG { // main method public static void main(String[] args) { // create hashmap HashMap<Integer, Integer> data = new HashMap<Integer, Integer>(); // add elements to the created hashmap data.put(1, 67); data.put(2, 34); // display the data System.out.println(data); // Create unmodifiable map for the above map Map<Integer, Integer> final1 = Collections.unmodifiableMap(data); // put value in unmodifiable map final1.put(3, 45); // display unmodifiable map System.out.println(final1); } }
Producción:
{1=67, 2=34} Exception in thread "main" java.lang.UnsupportedOperationException at java.util.Collections$UnmodifiableMap.put(Collections.java:1459) at GFG.main(GFG.java:21)
Publicación traducida automáticamente
Artículo escrito por manojkumarreddymallidi y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA