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


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

Java Collections 的 checkedNavigableMap() 方法是一種返回給定 Map 的動態和類型安全視圖的方法。任何插入錯誤類型元素的嘗試都將立即導致 ClassCastException。

用法:

public static <Key,Value> NavigableMap<Key,Value> checkedNavigableMap(NavigableMap<Key,Value> Map, Class<Key> keyType, Class<V> valueType)  

參數:



  1. Key是關鍵
  2. Value是價值
  3. Map是輸入圖
  4. keyType是鍵的數據類型
  5. valueType 是值的數據類型

返回:此方法將返回給定 Map 的動態且類型安全的視圖。

異常:

  • ClassCastException:ClassCastException 是當我們不正確地將類從一種類型轉換為另一種時在 Java 中引發的運行時異常。

例:

Java


// Java program to create typesafe 
// view from the map
import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // createa tree map
        NavigableMap<String, Integer> data
            = new TreeMap<>();
  
        // Insert values in the given map
        data.put("id1", 56);
        data.put("id2", 15);
        data.put("id3", 19);
        data.put("id4", 70);
  
        // Create type safe view of the given  Map
        System.out.println(Collections.checkedNavigableMap(
            data, String.class, Integer.class));
    }
}
輸出
{id1=56, id2=15, id3=19, id4=70}

範例2:

Java


// Java program to create
// typesafe view from the map
import java.util.*;
  
public class GFG {
    // main method
    public static void main(String[] args)
    {
        // createa tree map
        NavigableMap<String, String> data = new TreeMap<>();
  
        // Insert values in the giveb map
        data.put("id1", "sravan");
        data.put("id2", "manoj");
        data.put("id3", "sai");
        data.put("id4", "vignesh");
  
        // Create type safe view of the given  Map
        System.out.println(Collections.checkedNavigableMap(
            data, String.class, String.class));
    }
}
輸出
{id1=sravan, id2=manoj, id3=sai, id4=vignesh}



相關用法


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