IQ-HashMap


  • What is HashMap?

                  HashMap is Key Value pair. where Keys are unique.
------------------------


  • What is the difference between HashMap and ConcurrentHashMap?

            To get and put key-value pairs from hashmap, you have to calculate the hashcode and look for correct bucket location in array of Collection.Entry.
            In concurrentHashMap, the difference lies in internal structure to store these key-value pairs.

           ConcurrentHashMap has an addition concept of segments. It will be easier to understand it you think of one segment equal to one HashMap [conceptually].
           A concurrentHashMap is divided into number of segments [default 16] on initialization. ConcurrentHashMap allows similar number (16) of threads to access these segments concurrently so that each thread work on a specific segment during high concurrency.
------------------------


  • What is difference between hashmap & hashtable?

              The HashMap class is roughly equivalent to Hashtable, except that it is non synchronized and permits nulls.
             HashMap allows null values as key and value whereas Hashtable doesn't allow nulls. HashMap does not guarantee that the order of the map will remain constant over time.
------------------------


  • What is the difference between ConcurrentHashMap and Hashtable ?

               Both can be used in multithreaded environment but once the size of Hashtable becomes considerable large performance degrade because for iteration it has to be locked for longer duration.

               Since ConcurrentHashMap introduced concept of segmentation , no matter how large it becomes only certain part of it get locked to provide thread safety so many other readers can still access map without waiting for iteration to complete.

               In short ConcurrentHashMap only locked certain portion of Map while Hashtable lock full map while doing iteration.
------------------------


  • Why immutable object are prefered for Key in HashMap?

              The very basic need of hashcode in HashMap is to identify the bucket location where to put the key-value pair, and from where it has to be retrieved.

              If the hashcode of key object changes every time, the exact location of key-value pair will be calculated different, every time. This way, one object stored in HashMap will be lost forever and there will be very minimum possibility to get it back from map.

             For this same reason, key are suggested to be immutable, so that they return a unique and same hashcode each time requested on same key object.
------------------------


  • How does HashMap work ?

             HashMap works on the principle of hashing.
             put() and get() methods are used to store and retrieve data from hashmap.
             It has a number of buckets which stores key-value pairs.

            when put() is called, hashmap implementation calls hashcode() on the key to identify the bucket location then stores both key+value in the bucket
            when get() is called, the hashcode() on key is used to identify the bucket location and the value if returned.

            If two key objects have same hashcode, bucket location will be the same and collision occurs in hashmap.
            Inside the bucket, data is stored in linked list, so in collision scenario, it will get added to next node.
           So, when get() is called, the hashcode() would point to the bucket location, then the use key.equals() to find the correct node in the linked list.
------------------------


  • How does 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 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 is the requirement for an object to be used as key or value in HashMap?

            The key or value object must implement 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.
------------------------


  • How does HashMap handle collisions in Java?

              The java.util.HashMap uses chaining to handle collisions, which means new entries, an object which contains both key and values, are stored in a linked list along with existing value and then that linked list is stored in the bucket location.
             In the worst case, where all key has the same hashcode, your hash table will be turned into a linked list and searching a value will take O(n) time as opposed to O(1) time.
------------------------


  • Which data structure is used to implement HashMap in Java?

             Even though HashMap represents a hash table, it is internally implemented by using an array and linked list data structure in JDK.
            The array is used as bucket while a linked list is used to store all mappings which land in the same bucket.
            From Java 8 onwards, the linked list is dynamically replaced by binary search tree, once a number of elements in the linked list cross a certain threshold to improve performance.
------------------------


  • Does HashMap store duplicate Key & Values?

            No - Hashmap does not allow duplicate Key. But can contain duplicate value.
------------------------


  • Is HashMap thread-safe in Java? What will happen if you use HashMap in a multithreaded Java application?

                No, HashMap is not thread-safe in Java. You should not share an HashMap with multiple threads if one or more thread is modifying the HashMap.
                If you use HashMap in a multithreaded environment in such a way that multiple threads structurally modify the map e.g. add, remove or modify mapping then the internal data structure of HashMap may get corrupt
                i.e. some links may go missing, some may point to incorrect entries and the map itself may become completely useless.
               Hence, it is advised not to use HashMap in the concurrent application, instead, you should use a thread-safe map e.g. ConcurrentHashMap or Hashtable.
------------------------


  • In how many ways You can iterate HashMap in java?

                   By using keySet and iterator
                   By using entrySet and iterator
                   By using entrySet and enhanced for loop
                   By using keySet and get() method
------------------------


  • What is load factor in HashMap & how does it work?

               A load factor is a number which controls the resizing of HashMap when a number of elements in the HashMap cross the load factor e.g. if the load factor is 0.75 and when becoming more than 75% full then resizing trigger which involves array copy.
              First, the size of the bucket is doubled and then old entries are copied into a new bucket.
------------------------


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

              However, 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.
             This issue has been addressed in JDK 8 by introducing a new method called mappingCount() which returns a long value. So, you should use mappingCount() for large maps.
------------------------


  • What is an IdentityHashMap ? How is it different from a normal HashMap ?

             IdentityHashMap is similar to HashMap except that it uses reference equality when comparing elements.

             Instead of using the equals() method to compare entries as in HashMap, IdentityHashMap compares them using the == operator

             So, two object references are considered equal if they refer to the same object instance.
------------------------


  • What is a WeakHashMap ?

             A WeakHashMap implements a map that uses a weak reference to the keys.

            This allows an element in the map to be garbage-collected when the key is unused.

            It supports null values and the null key.

            WeakHashMap class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.

     Ex.
import java.util.WeakHashMap;
public class WeakHashMapDemo {

    public static void main(String[] args) {     
        WeakHashMap<Integer, String> weakhashmap = new WeakHashMap<>();
        weakhashmap.put(1, "John");
        weakhashmap.put(2, "Smith");
        System.out.println("WeakHashMap initial size :" + weakhashmap.size());
        System.gc();
        System.out.println("WeakHashMap size after GC :" + weakhashmap.size());
    }
}
------------------------


  • What is the difference between remove() and clear() methods in HashMap ?

             We can remove entries from HashMap using remove(key) or clear() methods.

            remove(key) removes the mapping for the key specified in parameter.

            clear() method removes all the entries from the HashMap and returns void.
------------------------


  • Difference between Map and HashMap ?

               Map is an interface where HashMap is the concrete class.
------------------------


  • Which is the Parent Class of PrinterStateReasons class?

                      HashMap
------------------------


  • Which interfaces are implemented by HashMap?

                Serializable,  Map,  Cloneable
------------------------


  • Which interfaces are implemented by PrinterStateReasons?

          PrintServiceAttribute, Serializable, Severity>,  Attribute,  Cloneable,  Map<PrinterStateReason
------------------------


  • Which are the subclasses for HashMap?

                       PrinterStateReasons, LinkedHashMap
------------------------


  • Which is the Parent Class of HashMap class?

                        AbstractMap
------------------------


  • What is the package name for HashMap class?

                       java.util


1 comment:

Home

Mastering Java Interview Questions: Your Comprehensive Guide         If you're preparing for a Java interview or just lookin...