Java 集合框架 unmodifiableMap() 方法



描述

Java 集合框架 unmodifiableMap() 方法用于返回指定映射的不可修改视图。

声明

以下是 java.util.Collections.unmodifiableMap() 方法的声明。

public static <K,V> Map<K,V> unmodifiableMap(Map<? extends K,? extends V> m)

参数

m − 这是要返回不可修改视图的映射。

返回值

  • 方法调用返回指定映射的不可修改视图。

异常

从可变的字符串、整数映射获取不可变映射示例

以下示例演示了 Java 集合框架 unmodifiableMap(Map) 方法的用法。我们创建了一个字符串和整数的映射对象。添加了一些条目,然后使用 unmodifiableMap(Map) 方法,我们检索了映射的不可变版本并打印了映射。

package com.tutorialspoint;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create map
      Map<String,Integer> map = new HashMap<String,Integer>();

      // populate the map
      map.put("1",1); 
      map.put("2",2);
      map.put("3",3);

      // create a immutable map
      Map<String,Integer> immutableMap = Collections.unmodifiableMap(map);

      System.out.println("Immutable map is :"+immutableMap);
   }
}

输出

让我们编译并运行上面的程序,这将产生以下结果。

Immutable map is :{1=1, 2=2, 3=3}

从可变的字符串、字符串映射获取不可变映射示例

以下示例演示了 Java 集合框架 unmodifiableMap(Map) 方法的用法。我们创建了一个字符串和字符串的映射对象。添加了一些条目,然后使用 unmodifiableMap(Map) 方法,我们检索了映射的不可变版本并打印了映射。

package com.tutorialspoint;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create map
      Map<String,String> map = new HashMap<String,String>();

      // populate the map
      map.put("1","TP"); 
      map.put("2","IS");
      map.put("3","BEST");

      // create a immutable map
      Map<String,String> immutableMap = Collections.unmodifiableMap(map);

      System.out.println("Immutable map is :"+immutableMap);
   }
}

输出

让我们编译并运行上面的程序,这将产生以下结果。

Immutable map is :{1=TP, 2=IS, 3=BEST}

从可变的字符串、对象映射获取不可变映射示例

以下示例演示了 Java 集合框架 unmodifiableMap(Map) 方法的用法。我们创建了一个字符串和 Student 对象的映射对象。添加了一些条目,然后使用 unmodifiableMap(Map) 方法,我们检索了映射的不可变版本并打印了映射。

package com.tutorialspoint;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class CollectionsDemo {
   public static void main(String[] args) {
      
      // create map
      Map<String,Student> map = new HashMap<String,Student>();

      // populate the map
      map.put("1",new Student(1, "Julie")); 
      map.put("2",new Student(2, "Robert"));
      map.put("3",new Student(3, "Adam"));

      // create a immutable map
      Map<String,Student> immutableMap = Collections.unmodifiableMap(map);

      System.out.println("Immutable map is :"+immutableMap);
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

输出

让我们编译并运行上面的程序,这将产生以下结果。

Immutable map is :{1=[ 1, Julie ], 2=[ 2, Robert ], 3=[ 3, Adam ]}
java_util_collections.htm
广告
© . All rights reserved.