A HashMap
is a part of Java’s collection framework and is used to store data in key-value pairs. It belongs to the java.util
package and implements the Map
interface. In a HashMap, each key is unique, and it maps to a single value. This means that the map cannot contain duplicate keys.
Features
- Unordered: The elements are not stored in any particular order.
- Allows null values and one null key: HashMap can have one
null
key and multiplenull
values. - Fast lookups: HashMap uses a hash table to store data, offering constant time complexity (
O(1)
) for the basic operations likeget()
andput()
, assuming the hash function disperses the elements properly.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.HashMap; public class Main { public static void main(String[] args) { // Creating a HashMap HashMap<Integer, String> fruits = new HashMap<>(); // Adding elements to the map fruits.put(1, "Apple"); fruits.put(2, "Banana"); fruits.put(3, "Orange"); // Retrieving an element System.out.println(fruits.get(1)); // Output: Apple // Checking if key exists if (fruits.containsKey(2)) { System.out.println("Key 2 is present."); } // Removing a key-value pair fruits.remove(3); // Printing the size of the map System.out.println("Size: " + fruits.size()); // Output: 2 } } |
Use Cases
- Database Caching: Store frequently accessed data in memory (e.g., user session data).
- Counting Frequency: Count occurrences of words, numbers, or objects (e.g., word count in a text).
- Storing Configuration Settings: Map setting names (keys) to values (e.g., system properties).
- Routing Tables: In networking, map destination addresses to next-hop routers.
- Game Development: Map game object IDs to their corresponding properties or states.