当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Collections unmodifiableNavigableMap()用法及代码示例


Java Collections 类的 unmodifiableNavigableMap() 方法用于获取指定导航Map的不可修改视图。

用法

以下是 unmodifiableNavigableMap() 方法的声明:

public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<? extends K, ? extends K> m)

参数

参数 描述 必需/可选
m 它是将返回不可修改视图的可导航Map。 Required

返回

unmodifiableNavigableMap() 方法返回指定可导航Map的不可修改视图。

异常

NA

兼容版本

Java 1.8 及以上

例子1

import java.util.*;
public class CollectionsUnmodifiableNavigableMapExample1 {
    public static void main(String[] args) {
    	  //Create object of hash map and Add values in the map
        NavigableMap<String,String> map = new TreeMap<String,String>();
        map.put("key1", "Java");
        map.put("key2", "Android");
        map.put("key3", "JavaScript");
        System.out.println("Initial Map:"+map);
        //Create unmodifiable navigable map
        NavigableMap<String,String> map2 = Collections.unmodifiableNavigableMap(map);
        System.out.println("Unmodifiable Navigable Map:" + map2);       
        map.put("key4", "JavaTpoint");
        System.out.println("Unmodifiable Navigable Map after adding:" + map2);
        }
}

输出:

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

例子2

import java.util.*;
public class CollectionsUnmodifiableNavigableMapExample2 {
    public static void main(String[] args) {
    	  NavigableMap<Integer, String> map = new TreeMap<>();
        map.put(1, "one");
        map.put(2, "two");
        System.out.println("Initial Unmodifiable Navigable Map:"+map);
        NavigableMap<Integer, String> map2 = Collections.unmodifiableNavigableMap(map);
        map2.put(3, "three");
        }
}

输出:

Initial Unmodifiable Navigable Map:{1=one, 2=two}
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableMap.put(Collections.java:1453)
	at myPackage.CollectionsUnmodifiableNavigableMapExample2.main(CollectionsUnmodifiableNavigableMapExample2.java:10)

例子3

import java.util.*;
public class CollectionsUnmodifiableNavigableMapExample3 {
	public static void main(String[] args) {
		NavigableMap<Integer, Integer> map = new TreeMap<>();
		map.put(1, 1001);
		map.put(2, 1002);
		map.put(3, 1003);
		map.put(4, 1004);
		map.put(5, 1005);
		System.out.println("Initial map:" + map);		
		NavigableMap<Integer, Integer> map2 = Collections.unmodifiableNavigableMap(map);	
	      map.remove(4, 1004);	    	     
    	      System.out.print("Unmodifiable navigable map after remove(4, 1004):"+map2);
	      }
}

输出:

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






相关用法


注:本文由纯净天空筛选整理自 Java Collections unmodifiableNavigableMap() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。