Top 33 Hashmap Interview Questions in Java
Today we will discuss the Top 33 Hashmap Interview Questions in Java. In the earlier posts,
we had discussed Company-wise interview questions
Let's see the Top 30 Hashmap Interview Questions in Java now...
These questions are solely on the basis of the face-to-face interview given by people and collected thereafter.
So let's get started...
Hashmap Interview Questions in Java
- What is Hashmap in java?(Full Answer)
Hashmap is one of the Collection classes in java which is since java 1.2. Hashmap stores the data in key-value pair. You can access the value by giving the key which use to store the value. - How we get and put values in Hashmap?
We can simply Put values in hashmap using the put(key, value) method of hashmap, and to get it we can simply use the get(key) method to retrieve the value. - What are things an object needs to be used as a key or value in the Hashmap?
The key or value object must implement the equals() and hashcode() method. The hash code is used when you insert the key object into the map while equals are used when you try to retrieve a value from the map. - What is the time complexity of basic operations get() and put() in HashMap class?
In HashMap, we have an average time complexity of O(1) for the put and get operations and space complexity of O(n). - What is a collision in HashMap?
A collision is a hash code collision in a HashMap, which is a situation where two or more key objects have the same final hash value and hence point to the same bucket location or array index. This scenario can occur because according to the equals and hashCode contract, two unequal objects in Java can have the same hash code. - How is collision handled with the hashmap implementation in Java?
HashMap handles the collision resolution by using the concept of chaining i.e., it stores the values in a linked list (or a balanced tree since Java8, depends on the number of entries). - What will happen if two different keys of HashMap return the same hashcode()?
If two keys of HashMap return the same hash code, then they will end up in the same bucket, hence collision will occur. They will be stored in a linked list together. - What is the threshold value after which bucket converted from linked list to Tree?
When there are at least 8 entries (TREEIFY_THRESHOLD) in a single bucket and the total number of buckets is more then 64 (MIN_TREEIFY_CAPACITY) then that single bucket will be transformed to a perfectly balanced red black tree node. - What is the threshold value after which Tree is converted back to the linked list?
There is a flag in hashmap UNTREEIFY_THRESHOLD whose value is 6 in a single bucket Then it's converted back to LinkedList. - How HashMap internally works in Java? (Full Answer)
- Which data structure is used to implement HashMap in Java?
Hashmap internally uses Array and LinkedList to store data. You can see the full answer to the above question. - How will you measure the performance of HashMap?
From JavaDocs: An instance of HashMap has two parameters that affect its performance: initial capacity and load factor.
The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created.
The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets. - How can you handle null keys in hashmaps?
The null key is handled specially in HashMap using 2 separate methods putForNullKey(V value) and getForNullKey().
The null key is mapped always to the 0th Index. This null key scenario is treated in isolated methods to eliminate null key code check and improve the performance of getting and put methods. The equals() and hashcode() methods are not used in the case of a null key in HashMap. - Can you store a null value inside HashMap in Java?
Yes, HashMap also allows null values; you can store as many null values as you want. - Is it possible to store multiple values under the same key using Java Hashmaps?
No, you will not be able to store duplicate keys in the hashmap. If you try to store a new value in a key already present in the hashmap, then the hashmap would simply replace it with the new one. - How does the put() method of HashMap works in Java?
The put() method of HashMap works in the principle of hashing. It is responsible for storing an object into the backend array. The hashcode() method is used in conjunction with a hash function to find the correct location for the object into the bucket. If a collision occurs, then the entry object which contains both key and value is added to a linked list, and that linked list is stored into the bucket location. - What will happen if you try to store a key which is already present in HashMap?
If you store an existing key in the HashMap, then it will override the old value with the new value.
- Can you store a duplicate key and value in HashMap?
You cannot store the duplicate keys in hashmap, but duplicate values can be stored with different keys like Key A and Key B can have the same value C. - What is the difference between HashMap and Hashtable in java?
1. The main difference between Hashtable and HashMap is that HashMap can contain one null key and any number of null values but Hashtable does not allow null values.
2. Hashtable is synchronized while HashMap is not synchronized.
3. HashMap is faster as compared to Hashtable because HashMap is not synchronized. - What is the difference between HashMap and ConcurrentHashMap in java?
1. HashMap is not thread-safe whereas ConcurrentHashMap is thread-safe which means at a time only one thread can access the code.
2. HashMap can contain one null key whereas ConcurrentHashMap does not allow keys to contain null values. - What is the difference between HashMap and Collections.synchroizedHashMap(map)?
The main difference between them is HashMap is non-synchronized while Collections.synchronizedHashMap(HashMap) is a wrapped instance of HashMap which has all put and get methods synchronized. - What is the difference between HashMap and ArrayList?
1. HashMap implements Map Interface while ArrayList class Implements List Interface.
2. Hashmap has no order guarantee while arraylist maintains the order.
3. Hashmap does not allow duplicate keys whereas ArrayList does allow duplicate objects. - What is the difference between HashMap and TreeMap in java?
1. Hashmap as mentioned above store no order while Treemap maintains elements in sorted order according to natural ordering of elements.
2. HashMap internally uses hashing while Treemap internally uses red black tree implementation.
3. HashMap con contain one null key and any number of null values while Treemap cannot contain null key but may contain null values. - Is HashMap thread-safe in Java?
No, HashMap is not at all thread-safe in java. You should not share HashMap with multi threaded code that is using and modifying Hashmap i.e inserting or removing a map value. Only Read-only functionality will not have any impact of multiple threads on Hashmap for getting values through key. - What will happen if you use HashMap in a multithreaded Java application?
If You use HashMap in multi threaded environment which modify structure of hashmap using add, remove operations then it lead to distorted map where You may endup having values which point to incorrect data, corrupted data, not able to get right value. Thus it is recommended not to use HashMap in multithreaded environment. To overcome this JDK has concurrent classes like ConcurrentHashMap which is thread safe map. - What are the different ways to iterate over HashMap in Java? (Full Answer)
1. Iterating over Map.entrySet() using For-Each loop
2.Iterating over keys or values using keySet() and values() methods
3.Iterating using iterators over Map.Entry<K, V>
4.Using forEach(action) method
5.Iterating over keys and searching for values - How do you remove a mapping while iterating over HashMap in Java?
Using Iterator Class remove() method we can remove mapping while iterating Hashmap.Iterator itr = map.entrySet().iterator(); while(itr.hasNext()){ Map.Entry current = itr.next(); if(current.getKey().equals("javacodegeek"){ itr.remove(); // this will remove the current entry. } }
- In which order mappings are stored in HashMap?
Data is stored in hashmap in random order. There is no guarantee of ordering even while retreiving you can get different order output while traversing same map multiple times. - Can you sort HashMap in Java?
No, You cannot sort Hashmap in Java, For sorted data we can use Treemap according to natural ordering. - What is the load factor in HashMap?
Load Factor is a number which controls resizing of HashMap When Hashmap reaches certain 0.75 Load Factor values then resizing triggers inside HashMap which involves array copy operation. - How does resizing happens in HashMap?
As mentioned in above answer if Hashmap bucket reaches 0.75 load factor values then resizing triggers which copy content of old entries to new bucket with bigger size.
- How many entries you can store in HashMap? What is the maximum limit?
There is no maximum limit for HashMap, you can store as many entries as you want because when you run out of the bucket, entries will be added to a linked list which can support an infinite number of entries, of course until you exhaust all the memory you have.
Btw, the size() method of HashMap return an int, which has a limit, once a number of entries cross the limit, size() will overflow, and if your program relies on that, then it will break. - What is the difference between the capacity and size of HashMap in Java?
The capacity denotes how many entries HashMap can store, and size denotes how many mappings or key/value pair is currently present.
Conclusion
That's it for the Top 33 Hashmap Interview Questions in Java. In this post, we have covered all the main questions that are being asked in interview rounds.
Thanks for reading this post so far. If you like this post then please share it with your friends and colleagues. If you have any questions, doubts, suggestions, or feedback then please drop a comment and I'll try to answer your question.
So what do you think about this post? Please share your experiences in the comments sections so we can update the list and help the community.
If you want answers as well for these questions please let me know in the comments section will update the post accordingly.
Happy Learning!!!
More Examples you may like
Comments
Post a Comment
If you have any doubts, Please let me know.