The containsKey()
method of EnumMap
is used to check if a value is mapped to the specified key
.
Note:
EnumMap
is similar toMap
, except thatEnumMap
only takes theEnum
type as a key. Also, all the keys must be from a singleenum
type. For further details, refer here.
public boolean containsKey(Object key)
The key to check is passed as an argument.
Note:
EnumMap
doesn’t allownull
keys, so if we passnull
as an argument, we will getfalse
as the result.
This method returns true
if the key has a mapping. Otherwise, it returns false
.
The example below shows how to use the containsKey()
method.
import java.util.EnumMap;class ContainsKey {enum Days{MON, TUE, WED, THUR, FRI, SAT, SUN};public static void main( String args[] ) {EnumMap<Days, String> map = new EnumMap<>(Days.class);map.put(Days.MON, "chest");System.out.println( "The map is" + map);System.out.println("Checking if the key Days.MON has mapping: "+ map.containsKey(Days.MON));System.out.println("Checking if the key Days.FRI has mapping: "+ map.containsKey(Days.FRI));System.out.println("Checking if the key null has mapping: "+ map.containsKey(null));}}
Line 1: We import the EnumMap
class.
Line 3: We create an enum
for days of the week with the name Days
.
Line 7: We create an EnumMap
object with the name map
.
Line 8: We use the put
method to add a mapping {Days.MON="chest"}
to the map
object.
Line 11: We use the containsKey
method to check if map
has a mapping for the key Days.MON
. We get true
as a result because the map has a mapping for the key Days.MON
.
Line 12: We use the containsKey
method to check if map
has a mapping for the key Days.FRI
. We get false
as a result because the map does not have mapping for the key Days.FRI
.
Line 13: We use the containsKey
method to check if map
has a mapping for the key null
. The EnumMap
doesn’t allow null
keys, so false
is returned.