HashMap ClassThe HashMap class is the most common implementation of the Map interface. It stores data in (Key, Value) pairs, and you can access them by an index of another type (e.g. a String).
It uses a hash table to store the map. This allows the execution time of get() and put() to remain constant (O(1)) on average, regardless of the size of the map.
HashMapnull: A HashMap can have one null key and multiple null values.get and put operations on average.HashMap WorksSimilar to HashSet, a HashMap uses the key's hashCode() method to determine where to store the (Key, Value) entry. When you want to retrieve a value, it uses the key's hashCode() to quickly find the location, and then uses the key's equals() method to find the exact entry.
Important: If you use custom objects as keys in a
HashMap, you must properly implement both thehashCode()andequals()methods in your key class.
HashMapHashMap is the ideal choice when you need to map keys to values and:
It is the most frequently used Map implementation in Java.
HashMap ExampleHere is an example demonstrating common operations on a HashMap.
import java.util.HashMap;public class Main { public static void main(String[] args) { // Create a HashMap object called capitalCities HashMap<String, String> capitalCities = new HashMap<String, String>(); // Add keys and values (Country, City) capitalCities.put("England", "London"); capitalCities.put("Germany", "Berlin"); capitalCities.put("Norway", "Oslo"); capitalCities.put("USA", "Washington DC"); System.out.println(capitalCities); // Access an item System.out.println("Capital of England: " + capitalCities.get("England")); // Remove an item capitalCities.remove("England"); System.out.println("After removing England: " + capitalCities); // Get the size System.out.println("Size of the map: " + capitalCities.size()); // Loop through a HashMap System.out.println("--- Looping through keys ---"); for (String country : capitalCities.keySet()) { System.out.println("key: " + country + " value: " + capitalCities.get(country)); } } }