Search Tutorials

Top Java HashMap and ConcurrentHashMap Interview Questions | JavaInUse

Top Java HashMap and ConcurrentHashMap Interview Questions.

In this post we will look at Java Hashmap interview questions. Examples are provided with explanation.

Q: What is equals method in Java ?
Apart from the primitives, everything in Java is an object which is extended by the Java.lang.Object. The equals()and other methods are defined in the Object class. So all java classes have the equals() method by default. To test if two object instances are equal we use the equals() method. It is recommended to override this method if we wish to compare the objects to test their equality based on the business requirements. If the equals method is not overridden, the default implementation of the equals method() inherited from the Object class will be used.
Overriding equals() in Java

Q: What is hashcode method in Java ?
Hashcode method generates hashcode which is used to select the bucket for storing data in Hashing based collections
Overriding hashcode() in Java

Q: Can we synchronize Hashmap?
We can synchronize the map using the synchonized keyword.
Map map= Collections.synchronizedMap(hashMap);

Q: Can we add duplicate keys in a HashMap?
Duplicate keys cannot be added in HashMap.

Q: Can you explain internal working of ConcurrentHashMap?
The ConcurrentHashMap class provides a concurrent version of the standard HashMap. So its functionality is similar to a HashMap, except that it has internally maintained concurrency. Depending upon the level of concurrency required the concurrent HashMap is internally divided into segments. If the level of concurrency required is not specified then it is takes 16 as the default value. So internally the ConcurrentHashMap will be divided into 16 segments. Each Segment acts independently. In previous versions of Java when you used-
    Map<String, Integer> conMap = new ConcurrentHashMap<>();
All the 16 segments would also get initialized immediately. Which means more memory consumption. In java 8 implementation of HashMap when we use
    Map<String, Integer> conMap = new ConcurrentHashMap<>();
all the 16 internal segments point to null. The segments get initialized only when data is inserted and the particular segment is to be used. So better memory usage.
Internal working of ConcurrentHashMap in Java.

Q: What is difference between Hashmap and ConcurrentHashMap?
Difference between Hashmap and ConcurrentHashMap in Java.

See Also

Spring Boot Interview Questions Apache Camel Interview Questions Drools Interview Questions Enterprise Service Bus- ESB Interview Questions. JBoss Fuse Interview Questions Top ElasticSearch frequently asked interview questions Angular 2 Interview Questions