📜  Java Collections checkedNavigableMap() 方法和示例

📅  最后修改于: 2022-05-13 01:55:35.556000             🧑  作者: Mango

Java Collections checkedNavigableMap() 方法和示例

Java Collections 的checkedNavigableMap () 方法是一种返回给定 Map 的动态且类型安全的视图的方法。任何插入错误类型元素的尝试都将立即导致 ClassCastException。

句法:

参数:

  1. 钥匙就是钥匙
  2. 价值就是价值
  3. 地图是输入地图
  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 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));
    }
}


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 data = new TreeMap<>();
 
        // Insert values in the given 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=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 data = new TreeMap<>();
 
        // Insert values in the given 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}