TreeMap containsKey(Object) in Java

containsKey(Object): This method is available in java.util.TreeMap class of Java.

Syntax:

boolean java.util.TreeMap.containsKey(Object key)

This method takes one argument. This method returns true if this map contains a mapping for the specified key.

Parameters: One parameter is required for this method.

key: key whose presence in this map is to be tested.

Returns: true if this map contains a mapping for the specified key.

Throws:

1. ClassCastException - if the specified key cannot be compared with the keys currently on the map.

2. NullPointerException - if the specified key is null and this map uses natural ordering, or its comparator does not permit null keys

Approach 1: When no exception

Java

import java.util.TreeMap;

public class TreeMapcontainsKey {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer key = 2;

        System.out.println(treeMap.containsKey(key));
    }
}

Output:

true


Approach 2: NullPointerException

Java

import java.util.TreeMap;

public class TreeMapcontainsKey {
    public static void main(String[] args) {

        TreeMap<Integer, String> treeMap =
new TreeMap<Integer, String>();

        treeMap.put(2, "Hello");
        treeMap.put(11, "Java");
        treeMap.put(23, "Program");
        treeMap.put(6, "C++");
        treeMap.put(25, "Program");

        Integer key = null;

        System.out.println(treeMap.containsKey(key));
    }
}

Output:

Exception in thread "main" java.lang.NullPointerException at java.base/java.util.Objects.requireNonNull(Objects.java:208) at java.base/java.util.TreeMap.getEntry(TreeMap.java:345) at java.base/java.util.TreeMap.containsKey(TreeMap.java:233)


No comments:

Post a Comment