Home » Java programming language

Java Collections checkedMap() Method with Example

Collections Class checkedMap() method: Here, we are going to learn about the checkedMap() method of Collections Class with its syntax and example.
Submitted by Preeti Jain, on January 07, 2020

Collections Class checkedMap() method

  • checkedMap() Method is available in java.lang package.
  • checkedMap() Method is used to return the typesafe view of the given Map at runtime.
  • checkedMap() Method is a static method, so it is accessible with the class name and if we try to access the method with the class object then we will not get an error.
  • checkedMap() Method does not throw an exception at the time of returning a validated list.

Syntax:

    public static Map checkedMap(Map map, Class key_ty, Class val_ty);

Parameter(s):

  • Map map – represents a map for which to get typesafe view of the given map.
  • Class key_ty – represents the key type that the given map is allowed to store.
  • Class val_ty – represents the value(val) type that the given map is allowed to store.

Return value:

The return type of the method is Map, it returns typesafe view of the given map dynamically.

Example:

// Java Program is to demonstrate the example
// of Map checkedMap(Map map, Class key_ty, Class val_ty)
// of Collections class

import java.util.*;

public class CheckedMap {
    public static void main(String args[]) {
        // Create a hashmap object    
        HashMap < Integer, String > hm = new HashMap < Integer, String > ();

        // By using put() method is to add the
        // given elements in hash map
        hm.put(20, "C");
        hm.put(10, "C++");
        hm.put(30, "JAVA");
        hm.put(40, "DOTNET");
        hm.put(50, "PHP");

        // Display HashMap
        System.out.println("link_list: " + hm);

        // By using checkedMap() method is to 
        // represent the type safe view of the given
        // Collection hashmap

        Map < Integer, String > map = Collections.checkedMap(hm, Integer.class, String.class);

        System.out.println();
        System.out.println("Collections.checkedMap(hm, Integer.class,String.class) :");

        // Display collection
        System.out.println("map: " + map);
    }
}

Output

link_list: {50=PHP, 20=C, 40=DOTNET, 10=C++, 30=JAVA}

Collections.checkedMap(hm, Integer.class,String.class) :
map: {50=PHP, 20=C, 40=DOTNET, 10=C++, 30=JAVA}


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.