In Java, HashMap is the implementation of the Map interface. HashMap offers various options to store and retrieve key-value pairs, where each unique key maps to a specific value.
HashMap Properties
- Underline data structure is HashTable.
- Duplicate keys are not allowed but duplicate values are allowed.
- Insertion order is not preserved.
- Heterogeneous objects are allowed.
- Null is allowed for key only once.
- Null is allowed for values any number of times.
- HashMap implements Map, Cloneable, and Serializable interfaces.
- HashMap is the best choice if our frequent operation is a search operation.
HashMap Constructor
HashMap()
HashMap map = new HashMap();
This constructor creates an empty HashMap object with a default initial capacity of 16 and a default load factor fill ratio of 0.75
HashMap(int initialCapacity )
public HashMap( @Range(from = 0, to = Integer.MAX_VALUE) int initialCapacity )
This constructor creates an empty HashMap object with the specified initial capacity and the default load factor / fill ration (0.75)
HashMap(int initialCapacity, float loadFactor )
public HashMap( @Range(from = 0, to = Integer.MAX_VALUE) int initialCapacity,
float loadFactor )
This constructor creates an empty HashMap object with the specified initial capacity and load factor/ fill ratio.
HashMap Java Implementation
package thecodedata;
import java.util.HashMap;
public class HashMapDemo {
public static void main(String[] args) {
HashMap map = new HashMap();
map.put(1, "The");
map.put(2, "Code");
map.put(3, "Data");
//Printing HashMap
System.out.println(map);
map.put(3, "Java");
System.out.println(map.get(3));
map.remove(3);
System.out.println(map);
}}
Difference Between HashMap and HashTable
HashMap | HashTable |
---|---|
All methods are non- synchronized | All methods are synchronized |
Not thread safe | thread safe |
Performance is high | Performance is low |
Null is allowed for both key and value | Null is not allowed for key and value |
Introduced in Java 1.2v | Introduced in Java 1.0v |