Ranjit Mane’s Post

🧩 20 #Java #Map #Interview #Questions 🔹 Basic Level 1. What is a Map in Java? → A Map is a collection that stores key-value pairs, where keys are unique. 2. What are the main implementations of Map in Java? → HashMap, LinkedHashMap, TreeMap, Hashtable, ConcurrentHashMap. 3. Can a Map have duplicate keys? → ❌ No, keys must be unique (latest value replaces old one). 4. Can a Map have duplicate values? → ✅ Yes, values can be duplicated. 5. What happens if you insert the same key again in a Map? → The old value is replaced with the new one. 6. What is the difference between Map and Collection? → Map stores key-value pairs, while Collection stores individual elements (List/Set). 7. What are the key differences between HashMap and Hashtable? Feature HashMap Hashtable Synchronization No Yes Null Keys/Values Allowed Not allowed Performance. Faster. Slower 8. What is the difference between HashMap and LinkedHashMap? → LinkedHashMap maintains insertion order; HashMap does not. 9. What is the difference between HashMap and TreeMap? → TreeMap stores keys in sorted order, HashMap is unordered. 10. Can we store null key or null value in Map? → HashMap allows one null key, multiple null values. TreeMap ❌ does not allow null keys 🔹 Intermediate Level 11. How does HashMap work internally? → It uses hashing: Hash code is computed for the key. Entry stored in a bucket (array + linked list/red-black tree). If hash collision → chaining or tree balancing. 12. What is load factor in HashMap? → The ratio (default 0.75) to decide when to resize the map. 13. What is initial capacity in HashMap? → Initial number of buckets (default 16). 14. What is the time complexity of get() and put() in HashMap? → Average: O(1) Worst (collision-heavy): O(n) 15. What is a collision in HashMap? How is it handled? → Two keys having the same hash → collision. It’s handled by linked list or balanced tree (since Java 8). 16. What is difference between keySet(), values(), and entrySet()? | Method | Returns | |---------|----------| | keySet() | All keys | | values() | All values | | entrySet() | All key-value pairs | 17. How to iterate through a Map in Java? for (Map.Entry<String, Integer> e : map.entrySet()) { System.out.println(e.getKey() + " : " + e.getValue()); } 18. What is ConcurrentHashMap? → A thread-safe version of HashMap — allows concurrent access without locking the entire map. 19. Why is Hashtable considered legacy? → It’s synchronized, slower, and replaced by ConcurrentHashMap. 20. What happens if two keys have the same hashCode but are not equal()? → They are stored in the same bucket, but compared using equals().

To view or add a comment, sign in

Explore content categories