Javatpoint Logo
Javatpoint Logo

Java EnumMap put() method

The put() method of Java EnumMap class is used to associate the given value with the given key in this EnumMap.

Syntax

Parameters

key - the key with which the given value is to be associated

value - the value to be associated with the given key

Returns

This method returns the old value associated with the specified key.

  • This method returns old value if this map already contained a mapping for this key.
  • This method returns null if there was no mapping for the specified key.

Exception

NullPointerException - if the specified key is null.

Example 1

Test it Now

Output:

Map: {Java=1, Python=2, PHP=3, Android=4}
Updated Map: {Java=20, Python=2, PHP=3, Android=4, Javascript=5}
First update returns: null
Second update returns: 1

Example 2

Test it Now

Output:

Map: {January=1, February=2, March=3, April=4}
Updated Map: {January=1, February=2, March=15, April=4, May=5}
First update returns: null
Second update returns: 3

Example 3

Test it Now

Output:

Map: {Monday=1, Tuesday=2, Wednesday=3}
Exception in thread "main" java.lang.NullPointerException
	at java.util.EnumMap.typeCheck(Unknown Source)
	at java.util.EnumMap.put(Unknown Source)
	at EnumMapPutExample3.main(EnumMapPutExample3.java:18)
Next TopicJava EnumMap



Please Share

facebook twitter google plus pinterest