Java Utility Library

Java Collections - checkedNavigableMap() Method



The java.util.Collections.checkedNavigableMap() method returns a dynamically typesafe view of the specified navigable map. Any attempt to insert a mapping whose key or value have the wrong type will result in an immediate ClassCastException.

Syntax

public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m,
                                                          Class<K> keyType,
                                                          Class<V> valueType)

Here, K and V are the type of keys and values in the navigable map.


Parameters

m Specify the navigable map for which a dynamically typesafe view is to be returned.
keyType Specify the type of key that m is permitted to hold.
valueType Specify the type of value that m is permitted to hold.

Return Value

Returns a dynamically typesafe view of the specified navigable map.

Exception

NA.

Example:

In the example below, the java.util.Collections.checkedNavigableMap() method returns a dynamically typesafe view of the given navigable map.

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //creating a NavigableMap object
    NavigableMap<Integer, String> MyMap = new TreeMap<Integer, String>();

    //populating MyMap
    MyMap.put(101, "John");
    MyMap.put(102, "Marry");
    MyMap.put(103, "Kim");

    //printing the map
    System.out.println("MyMap contains: " + MyMap); 

    //creating a dynamically typesafe view
    //of the navigable map
    NavigableMap NewMap = 
      Collections.checkedNavigableMap(MyMap, Integer.class, String.class);

    //printing the map
    System.out.println("NewMap contains: " + NewMap); 
  }
}

The output of the above code will be:

MyMap contains: {101=John, 102=Marry, 103=Kim}
NewMap contains: {101=John, 102=Marry, 103=Kim}

❮ Java.util - Collections