Hashmap was first introduced in Java 1.2.The Hashmap class is included in the java.util package.The data in a hashmap is stored in two parts: the key and the value, which can be accessed using an index of another type.A hashmap have unique keys , inserting a duplicate key will replace the data of the key.
Hashmap class have many inbuilt method, one of those method is hashmap clear(). To know more about Java Hashmap clear() method read the complete article
Java Hashmap clear() Method
The hashmap clear() method clears the data of a hashmap , the keys and the values. this method does not take any parameters. Below in this page you can find it’s syntax, return values, parameters with detailed examples.
import java.util.*;
public class Main
{
public static void main (String[]args)
{
// Creating an empty HashMap
HashMap < Integer, String > hash_map = new HashMap < Integer, String > ();
// Mapping string values to int keys
hash_map.put (10, "Java");
hash_map.put (20, "Hashmap");
hash_map.put (25, "clear");
hash_map.put (30, "method");
// Displaying the HashMap
System.out.println ("Initial :" + hash_map);
// Clearing the hash map using clear()
hash_map.clear ();
// Displaying the final HashMap
System.out.println ("Finally the hashmap is empty: " + hash_map);
}
}
Output :
Initial :{20=Hashmap, 25=clear, 10=Java, 30=method}
Finally the hashmap is empty: {}
What happened above:In the above example a hashmap is created and elements are inserted in the hashmap. When the clear() method caleed it removes the key and the value corresponding to that key.
NoteIn Java the functionality of clear() method can be achieved by reinitializing the hashmap.
Login/Signup to comment