remove(Object): This method is available in java.util.Hashtable class of Java.
Syntax:
V java.util.Hashtable.remove(Object key)
This method takes one argument. This method removes the key (and its corresponding value) from this hashtable.
Note: This method does nothing if the key is not in the hashtable.
Parameters: One parameter is required for this method.
key: the key that needs to be removed.
Returns: the value to which the key had been mapped in this hashtable, or null if the key did not have a mapping.
Throws:
NullPointerException - if the key is null
Approach 1: When no exception
Java
import java.util.Hashtable;public class Hashtableremove {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);Object key = "Hello";hashtable.remove(key);System.out.println(hashtable);}}
Output:
{World=2}
Approach 2: NullPointerException
Java
import java.util.Hashtable;public class Hashtableremove {public static void main(String[] args) {Hashtable<String, Integer> hashtable =new Hashtable<String, Integer>();hashtable.put("Hello", 1);hashtable.put("World", 2);Object key = null;hashtable.remove(key);System.out.println(hashtable);}}
Output:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Object.hashCode()" because "key" is null at java.base/java.util.Hashtable.remove(Hashtable.java:508)
No comments:
Post a Comment