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

Understand browser, context, and page in Playwright

๐ŸŽฅ Playwright: Browser, Context & Page - Real-time Demo and Multi-User Testing  . ๐ŸŽฏ Goal: Understand browser , context , and page in Playwright ๐Ÿง  1. What is a browser ? ✅ Definition: A browser in Playwright is a launched instance of a real browser (Chromium, Firefox, WebKit) that can be used for automated testing. ✅ Purpose: It starts and controls the browser process. It is the root of your test execution. Required to create contexts and pages . ✅ Code Example: ts Copy Edit import { chromium } from 'playwright' ; const browser = await chromium. launch ({ headless : false }); ๐Ÿง  2. What is a context (browser context)? ✅ Definition: A context is like a separate browser profile (or incognito tab) inside the browser. Each context is isolated — no cookies, local storage, or sessions are shared. ✅ Purpose: Simulates multiple users or sessions. Enables parallel and isolated testing. Allows setting user-specific prefer...

How to Maximize a Browser window using Playwright Java

  Playwright itself does not have a direct maximize () method like some other browser automation tools, but you can achieve the effect by setting the viewport to the screen size of your display. Below are ways to handle Maximize a browser in Playwright Java  ร˜   Setting the viewport to the screen size  o    setViewportSize(1920, 1080): This sets the browser window to a full HD resolution, effectively maximizing it. o    setHeadless(false): Ensures the browser runs in a visible mode so you can see the window being maximized.  Code Snapshot  Playwright playwright = Playwright. create ()   ;   Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));     // Create a new browser context   BrowserContext context = browser.newContext(new Browser.NewContextOptions()          .setViewportSize(1920, 1080));     ...

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...