containsKey(Object): This method is available in java.util.Hashtable class of Java.
Syntax:
boolean java.util.Hashtable.containsKey(Object key)
This method takes one argument. This method tests if the specified object is a key in this hashtable.
Parameters: One parameter is required for this method.
key: possible key.
Returns: true if and only if the specified object is a key in this hashtable, as determined by the equals method; false otherwise.
Throws:
NullPointerException - if the key is null.
Approach 1: When no exception
Java
import java.util.Hashtable;public class HashtablecontainsKey {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);String key = "Hello";System.out.println(hashtable.containsKey(key));}}
Output:
true
Approach 2: NullPointerException
Java
import java.util.Hashtable;public class HashtablecontainsKey {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);String key = null;System.out.println(hashtable.containsKey(key));}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()" because "key" is null at java.base/java.util.Hashtable.containsKey(Hashtable.java:353)
No comments:
Post a Comment