TreeMap in Java

TreeMap (Since Java1.2): Underlying data structure is Red-Black tree. Insertion order is not preserved since objects will be inserted based on some sorting technique. If you use your own sorting order using Comprator then the key objects need not be Homogenous and Comparable. No restriction on Values. They can be heterogeneous and non-comparable. Duplicate keys […]

Difference between HashMap and WeakHashMap in Java

It is exactly same as HashMap except the below difference. HashMap object is not eligible for Garbage collector even though it does not have any external references if it associated with HashMap. Key of WeakHashMap has weak reference. I.e if the key is garbage collected, and then entry in WeakHashMap object will be deleted automatically. […]

Difference between HashMap and IndentityHashMap

It is exactly same as HashMap except the below difference. HashMap uses equals() method to indentify duplicate keys for object’s content comparision. IndentityHashMap uses ‘==’ operator to identify duplicate keys. Example :  In this example we are creating HashMap and IndentityHashMap objects and inserting integer values.  

 Output:

HashMap uses equals method for […]

HashMap example with hashCode and equals method in Java

In this tutorial, we will see the importance of hashCode and equals method while writing code by using HashMap. We will see first what the default behaviour of these methods and later will see how to override these methods. Both hashCode() and equals() method are defined in Java.lang.Object class. hashCode () : public navtive int […]

How HashMap works internally in Java

This question is asking in most of the java interviews. Let’s see the story of HashMap. How HashMap works in Java?   It works based on hashing. Hashing is nothing but, Creating and Assigning a unique code to the object. There is a method called “hash (int h) “in HashMap class to do this. From Java […]

java-logo

How To Sort Hashmap By Value in Java

In real-time, you may be getting hashmap result from the server and you want to display the hashmap values in sorted order Or you may need to display the values in a drop down but in a sorted order. For example, from server we are getting different types of pizza’s with the item as key […]