📜  Java中的集合 unmodifiableMap() 方法和示例

📅  最后修改于: 2022-05-13 01:58:09.453000             🧑  作者: Mango

Java中的集合 unmodifiableMap() 方法和示例

Java.util.Collections类的unmodifiableMap()方法用于返回指定地图的不可修改视图。此方法允许模块为用户提供对内部地图的“只读”访问权限。对返回的映射“通读”到指定映射的查询操作,并尝试修改返回的映射,无论是直接还是通过其集合视图,都会导致 UnsupportedOperationException。

如果指定的映射是可序列化的,则返回的映射将是可序列化的

句法:

public static  Map 
    unmodifiableMap(Map m)

参数:此方法将地图作为要为其返回不可修改视图的参数。

返回值:此方法返回指定地图的不可修改视图

以下是说明unmodifiableMap()方法的示例

示例 1:

// Java program to demonstrate
// unmodifiableMap() method
// for  value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv) throws Exception
    {
  
        try {
  
            // creating object of Hashtable
            Hashtable
                table = new Hashtable();
  
            // populate the table
            table.put("key1", "1");
            table.put("key2", "2");
            table.put("key3", "3");
  
            // getting unmodifiable map
            // using unmodifiableMap() method
            Map m = Collections
                                        .unmodifiableMap(table);
  
            // printing the unmodifiableMap
            System.out.println("Initial collection: " + table);
        }
  
        catch (UnsupportedOperationException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
Initial collection: {key3=3, key2=2, key1=1}

示例 2:对于UnsupportedOperationException

// Java program to demonstrate
// unmodifiableMap() method
// for  value
  
import java.util.*;
  
public class GFG1 {
    public static void main(String[] argv)
        throws Exception
    {
  
        try {
  
            // creating object of Hashtable
            Hashtable
                table = new Hashtable();
  
            // populate the table
            table.put("key1", "1");
            table.put("key2", "2");
            table.put("key3", "3");
  
            // getting unmodifiable map
            // using unmodifiableMap() method
            Map m = Collections
                                        .unmodifiableMap(table);
  
            // printing the unmodifiableMap
            System.out.println("Initial collection: "
                               + table);
  
            // Adding element to new Collection
            System.out.println("\nTrying to modify"
                               + " the unmodifiablemap");
            m.put("key4", "4");
        }
  
        catch (UnsupportedOperationException e) {
            System.out.println("Exception thrown : " + e);
        }
    }
}
输出:
Initial collection: {key3=3, key2=2, key1=1}

Trying to modify the unmodifiablemap
Exception thrown : java.lang.UnsupportedOperationException