Javatpoint Logo
Javatpoint Logo

Java Collections checkedMap() Method

The checkedMap() is an inbuilt method of Java Collections class. This method is used to get a dynamically typesafe view of the specified Map. If any attempt of insert mapping whose key or value has the wrong type, it will result in an immediate ClassCastException.

Syntax

Following is the declaration of checkedMap() method:

Parameter

Parameter Description Required/Optional
m It is the map for which a dynamically typesafe view is to be returned. Required
keyType It is the type of key that map m is permitted to hold. Required
valueType It is the type of value that map m is permitted to hold. Required

Returns

The checkedMap() method returns a dynamically typesafe view of the specified Map.

Exceptions

ClassCastException

Compatibility Version

Java 1.5 and above

Example 1

Test it Now

Output:

Type safe view of the Map is: {A=11, B=12, C=13, V=14}

Example 2

Test it Now

Output:

Map  Element: {1=One, 2=Two, 3=Three}
{1=One, 2=Two, 3=Three, Four=4}

Example 3

Test it Now

Output:

Map content: {Rahul=3, Amit=4, Raj=1, JavaTpoint=2}
Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer key into map with key type class java.lang.String
	at java.base/java.util.Collections$CheckedMap.typeCheck(Collections.java:3575)
	at java.base/java.util.Collections$CheckedMap.put(Collections.java:3621)
	at myPackage.CollectionCheckedMapExample3.main(CollectionCheckedMapExample3.java:13)






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA