Skip to main content

What is HashMap and HashTable in Java?

 

What is HashMap in Java?

A HashMap in Java is a part of the java.util package that implements the Map interface. It is a key-value pair-based data structure that uses a hashing mechanism to store and retrieve elements efficiently.

Key Features of HashMap

  • Allows null values but only one null key.
  • No duplicate keys are allowed, but values can be duplicated.
  • Unordered collection – does not maintain the insertion order.
  • Not thread-safe – must be synchronized externally if used in multithreading.
  • Uses hashing to store keys in buckets, improving retrieval speed.

How HashMap Works Internally?

  1. Hashing Mechanism:
    • The hashCode() method determines the bucket index.
    • It uses (hashCode % capacity) to store the key-value pair.
  2. Collision Handling:
    • If two keys generate the same bucket index, chaining (Linked List in Java 7, Balanced Tree in Java 8) is used to store multiple entries.

Example of HashMap

java
import java.util.HashMap; import java.util.Map; public class HashMapExample { public static void main(String[] args) { // Creating a HashMap HashMap<Integer, String> map = new HashMap<>(); // Adding key-value pairs map.put(1, "Java"); map.put(2, "Python"); map.put(3, "C++"); map.put(null, "NullKey"); // Allowed map.put(4, null); // Null values are allowed // Accessing elements System.out.println("Value for key 2: " + map.get(2)); // Iterating over HashMap for (Map.Entry<Integer, String> entry : map.entrySet()) { System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue()); } // Checking if a key exists System.out.println("Contains key 1? " + map.containsKey(1)); // Checking if a value exists System.out.println("Contains value 'Python'? " + map.containsValue("Python")); // Removing an element map.remove(3); System.out.println("After removing key 3: " + map); } }

Output:

yaml
Value for key 2: Python Key: 1, Value: Java Key: 2, Value: Python Key: 3, Value: C++ Key: null, Value: NullKey Key: 4, Value: null Contains key 1? true Contains value 'Python'? true After removing key 3: {1=Java, 2=Python, null=NullKey, 4=null}

Difference Between HashMap and HashTable

FeatureHashMapHashTable
Thread-SafetyNot synchronized (Not thread-safe)Synchronized (Thread-safe)
PerformanceFaster as it is not synchronizedSlower due to synchronization
Null Key/ValuesAllows one null key and multiple null valuesDoes not allow null keys or values
Iteration OrderNo guarantee of iteration orderNo guarantee of iteration order
Fail-FastYes (modifies structure while iterating throws ConcurrentModificationException)No fail-fast behavior

Example: HashTable

java
import java.util.Hashtable; public class HashTableExample { public static void main(String[] args) { Hashtable<Integer, String> table = new Hashtable<>(); table.put(1, "Java"); table.put(2, "Python"); // table.put(null, "NullKey"); // Throws NullPointerException // table.put(3, null); // Throws NullPointerException System.out.println("Hashtable: " + table); } }

Common Interview Questions & Answers on HashMap

1. What is HashMap and how does it work?

Answer: HashMap is a part of java.util package that implements Map interface, storing key-value pairs using a hashing mechanism. It uses the hashCode() method to compute the index of the key-value pair and stores them in buckets.


2. How does HashMap handle collisions?

Answer: HashMap handles collisions using chaining:

  • Java 7 and earlier: Uses a Linked List in each bucket.
  • Java 8 and later: Uses Balanced Tree (Red-Black Tree) when bucket size exceeds 8 elements to optimize performance.

3. Why is HashMap not thread-safe?

Answer: HashMap is not synchronized, meaning multiple threads accessing and modifying it simultaneously can lead to race conditions and data inconsistencies.

Solution?

Use:

  1. ConcurrentHashMap for a thread-safe version.
  2. Collections.synchronizedMap(new HashMap<>()) for manual synchronization.

4. What happens if two keys have the same hashCode?

Answer: If two keys have the same hashCode, they are placed in the same bucket. The second key is stored in a linked list (Java 7) or Red-Black Tree (Java 8) at that bucket location.


5. What is the default initial capacity and load factor of HashMap?

Answer:

  • Default capacity = 16
  • Default load factor = 0.75 (Resize happens when the HashMap is 75% full)

6. How does resizing work in HashMap?

Answer: When the number of elements exceeds (capacity × load factor), the capacity is doubled, and elements are rehashed (recomputed and stored in new locations).


7. Difference Between HashMap, LinkedHashMap, and TreeMap?

FeatureHashMapLinkedHashMapTreeMap
OrderingNo orderMaintains insertion orderSorted by keys (Natural Ordering)
PerformanceO(1)O(1)O(log n)
Null KeyAllowedAllowedNot allowed

8. What is fail-fast behavior in HashMap?

Answer: If a HashMap is modified structurally while iterating using an Iterator, it throws a ConcurrentModificationException.

Example

java
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class FailFastExample { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Python"); Iterator<Map.Entry<Integer, String>> iterator = map.entrySet().iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); map.put(3, "C++"); // Causes ConcurrentModificationException } } }

9. How do you make HashMap thread-safe?

Answer: Use:

  1. Collections.synchronizedMap(new HashMap<>())
  2. ConcurrentHashMap (recommended)

10. Why is HashMap faster than TreeMap?

Answer: HashMap provides O(1) time complexity for get/put operations, whereas TreeMap uses O(log n) as it uses a Red-Black tree for sorting.


Conclusion

  • HashMap is a widely used data structure for fast key-value retrieval.
  • Handles collisions using chaining (Linked List or Tree).
  • Not synchronized, use ConcurrentHashMap for thread safety.
  • Resizing & rehashing happens automatically when it reaches the load factor.

Comments

Popular posts from this blog

Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript)

๐ŸŽฅ Setup Browser, Context, Page & Run Config Test Scripts with package.json & playwright.config.js Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript) 1. Install Playwright You can install Playwright using the following command: npm init playwright@latest 2. Create a Basic Test Script Understand the core Playwright architecture: Element Description browser Controls the browser instance (like Chrome, Firefox, etc.) context Acts like a separate browser profile (cookies, localStorage are isolated) page A single browser tab where interaction happens 3. Run the Test npx playwright test example.spec.js Ways to Run TypeScript Tests Way Command Notes ๐ŸŸข Via npx npx playwright test Uses built-in TypeScript support ๐ŸŸข With s...

Playwright Test Structure in Details -Session-02

๐ŸŽฅ Playwright: test.only, Hooks & Grouping with test.describe Explained Let’s go step-by-step , showing how to build from a single test , to using beforeEach / afterEach , and then organizing things with test.describe . ✅ Step 1: Basic Single Test with test.only import { test, expect } from '@playwright/test' ; test. only ( '๐Ÿš€ Basic test - check title' , async ({ page }) => { await page. goto ( 'https://example.com' ); await expect (page). toHaveTitle ( /Example Domain/ ); }); test.only ensures only this test runs — great for debugging. ✅ Step 2: Add beforeEach and afterEach import { test, expect } from '@playwright/test' ; test. beforeEach ( async ({ page }) => { console . log ( '๐Ÿ”„ Setting up before each test' ); await page. goto ( 'https://example.com' ); }); test. afterEach ( async ({ page }, testInfo) => { console . log ( `๐Ÿ“ฆ Finished test: ${testInfo.title} `); }); test. only ( ...

Playwright Locators in JavaScript (Complete Guide)

๐ŸŽฏ Playwright Locators in JavaScript (Complete Guide) This guide explains each Playwright locator with: ✅ What it is ๐Ÿ• When to use ⚙️ How to use it ๐ŸŽฏ Benefits ๐Ÿงช Code Examples ๐Ÿ”น 1. Locator by ID ✅ What: Selects an element with a unique id . ๐Ÿ• When: Element has a unique id . ⚙️ How: page.locator('#username') ๐ŸŽฏ Benefit: Fast and reliable. <input id="username" /> await page.locator('#username').fill('John'); ๐Ÿ”น 2. Locator by Class ✅ What: Selects by class . ๐Ÿ• When: Repeated or styled elements. ⚙️ How: page.locator('.password') ๐ŸŽฏ Benefit: Useful for shared styling. <input class="password" /> await page.locator('.password').fill('12345'); ๐Ÿ”น 3. Locator by Text ✅ What: Matches visible element text. ๐Ÿ• When: For buttons, links, etc. ⚙️ How: page.getByText('Login') ๐ŸŽฏ Benefit: Human-readable. <button>Login...