Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaJava Collections checkedNavigableMap() Method with Examples

Java Collections checkedNavigableMap() Method with Examples

The checkedNavigableMap() method of Java Collections is a method that returns a  dynamically and typesafe view of the given Map. Any attempt to insert an element of the wrong type will result in an immediate ClassCastException.

Syntax:

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

Parameters:

  1. Key is the Key
  2. Value is the Value
  3. Map is the input map
  4. keyType is the data type of the key
  5. valueType is the data type of the value

Return: This method will return the dynamically and typesafe view of the given Map.

Exceptions:

  • ClassCastException: ClassCastException is a runtime exception raised in Java when we improperly cast a class from one type to another.

Example:

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));
    }
}


 
 

Output

{id1=56, id2=15, id3=19, id4=70}

 

Example 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 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));
    }
}


 
 

Output

{id1=sravan, id2=manoj, id3=sai, id4=vignesh}

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments