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


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

java 集合中的unmodifiableMap() 用於獲取給定Map的不可修改視圖。

用法:

public static <Key,Value> Map<Key,Value> unmodifiableMap(Map<? extends Key, ? extends Key> map)

參數:

  • Key是鍵值類型
  • Value是值類型
  • map是輸入圖

返回:它將返回給定Map的不可修改視圖。

異常:此方法不會拋出任何異常。

示例 1:

Java


// Java program to create a map with
// string values and get the
// unmodifiable view
import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create hashmap
        HashMap<String, String> data
            = new HashMap<String, String>();
  
        // add elements to the created hashmap
        data.put("1", "manoj");
        data.put("2", "sai");
        data.put("3", "ramya");
        data.put("4", "sravan");
  
        // display the data
        System.out.println(data);
  
        // Create unmodifiable map  for the above map
        Map<String, String> final1
            = Collections.unmodifiableMap(data);
  
        // display unmodifiable map
        System.out.println(final1);
    }
}
輸出
{1=manoj, 2=sai, 3=ramya, 4=sravan}
{1=manoj, 2=sai, 3=ramya, 4=sravan}

示例 2:

Java


// Java program to create a map 
// with integer values and get
// the unmodifiable view
import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // create hashmap
        HashMap<Integer, Integer> data
            = new HashMap<Integer, Integer>();
  
        // add elements to the created hashmap
        data.put(1, 67);
        data.put(2, 34);
  
        // display the data
        System.out.println(data);
  
        // Create unmodifiable map  for the above map
        Map<Integer, Integer> final1
            = Collections.unmodifiableMap(data);
  
        // display unmodifiable map
        System.out.println(final1);
    }
}
輸出
{1=67, 2=34}
{1=67, 2=34}

示例 3:當我們將元素添加到可修改的Map時,它會拋出錯誤。

Java


import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
  
        // create hashmap
        HashMap<Integer, Integer> data
            = new HashMap<Integer, Integer>();
  
        // add elements to the created hashmap
        data.put(1, 67);
        data.put(2, 34);
  
        // display the data
        System.out.println(data);
  
        // Create unmodifiable map  for the above map
        Map<Integer, Integer> final1
            = Collections.unmodifiableMap(data);
  
        // put value in unmodifiable map
        final1.put(3, 45);
  
        // display unmodifiable map
        System.out.println(final1);
    }
}

輸出:

{1=67, 2=34}
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.put(Collections.java:1459)
    at GFG.main(GFG.java:21)

相關用法


注:本文由純淨天空篩選整理自manojkumarreddymallidi大神的英文原創作品 Java Collections unmodifiableNavigableMap() Method with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。