當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。