Java Collections unmodifiableMap()

unmodifiableMap() 用于获取指定Map的不可修改视图。

1 语法

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

2 参数

m:该Map将返回不可修改的视图。

3 返回值

返回指定Map的不可修改视图。

4 unmodifiableMap()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.unmodifiableMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create object of hash map and Add values in the map
        HashMap<String,String> map = new HashMap<String,String>();
        map.put("key1", "Java");
        map.put("key2", "Android");
        map.put("key3", "JavaScript");
        System.out.println("Initial collection: "+map);
        //Create unmodifiable map
        Map<String,String> map2 = Collections.unmodifiableMap(map);
        System.out.println("Unmodifiable Map: " + map2);
        map.put("key4", "Yiidian");
        System.out.println("Unmodifiable Map after adding: " + map2);
    }
}

输出结果为:

Initial collection: {key1=Java, key2=Android, key3=JavaScript}
Unmodifiable Map: {key1=Java, key2=Android, key3=JavaScript}
Unmodifiable Map after adding: {key1=Java, key2=Android, key3=JavaScript, key4=Yiidian}

5 unmodifiableMap()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.unmodifiableMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "one");
        map.put(2, "two");
        System.out.println("Initial Unmodifiable Map: "+map);
        Map<Integer, String> map2 = Collections.unmodifiableMap(map);
        map2.put(3, "three");
    }
}

输出结果为:

Initial Unmodifiable Map: {1=one, 2=two}
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
	at com.yiidian.Demo.main(Demo.java:19)

6 unmodifiableMap()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.unmodifiableMap的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(1, 1001);
        map.put(2, 1002);
        map.put(3, 1003);
        map.put(4, 1004);
        map.put(5, 1005);
        System.out.println("Unmodifiable map: " + map);
        Map<Integer, Integer> map2 = Collections.unmodifiableMap(map);
        map.remove(4, 1004);
        System.out.print("Unmodifiable map after remove(4, 1004): "+map2);
    }
}

输出结果为:

Unmodifiable map: {1=1001, 2=1002, 3=1003, 4=1004, 5=1005}
Unmodifiable map after remove(4, 1004): {1=1001, 2=1002, 3=1003, 5=1005}

 

热门文章

优秀文章