interview questions and answers on Hash Map in java

0

 interview questions and answers on Hash Map in java


1. What is a HashMap in Java?

Answer: A HashMap is a class in Java Collections that implements the Map interface and stores key-value pairs in a hash table.


2. How does a HashMap work in Java?

Answer: A HashMap uses a hash function to map the keys to their corresponding values in a hash table. The hash function generates an index for each key-value pair, and this index is used to store and retrieve the value associated with that key.


3. What is the difference between HashMap and Hashtable in Java?

Answer: HashMap is not synchronized, whereas Hashtable is synchronized. Additionally, HashMap permits null values and keys, whereas Hashtable does not allow null values or keys.


4. How do you add a key-value pair to a HashMap in Java?

Answer: You can add a key-value pair to a HashMap in Java using the put() method. For example, hashMap.put(key, value).


5. How do you retrieve a value from a HashMap in Java?

Answer: You can retrieve a value from a HashMap in Java using the get() method. For example, hashMap.get(key).


6. What happens if you add a duplicate key to a HashMap in Java?

Answer: If you add a duplicate key to a HashMap in Java, the new value associated with that key will replace the old value.


7. How do you check if a key exists in a HashMap in Java?

Answer: You can check if a key exists in a HashMap in Java using the containsKey() method. For example, hashMap.containsKey(key).


8. How do you remove a key-value pair from a HashMap in Java?

Answer: You can remove a key-value pair from a HashMap in Java using the remove() method. For example, hashMap.remove(key).


9. How do you iterate through a HashMap in Java?

Answer: You can iterate through a HashMap in Java using a for-each loop or an iterator. For example:

            for (Map.Entry<String, Integer> entry : hashMap.entrySet())

           {

            String key = entry.getKey();

            Integer value = entry.getValue();

            // Do something with the key-value pair

            }


10. What is the default capacity and load factor of a HashMap in Java?

      Answer: The default initial capacity of a HashMap in Java is 16, and the default      load factor is 0.75. This means that the HashMap will automatically resize when the number of elements exceeds 75% of the initial capacity.




Post a Comment

0Comments
Post a Comment (0)