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 […]

PriorityQueue Example in java

PriorityQueue(Since Java 1.5) : It is an unbounded priority queue based on priority heap. The elements of the priority queue are ordered according to the constructor which you use. PriorityQueue pq = new PriorityQueue() It creates empty priority queue with default initial capacity 11. Priority order is natural sorting order. PriorityQueue pq = new PriorityQueue(int […]

TreeSet in java

TreeSet(Since Java 1.2) Underlying data structure is balanced tree. Duplicates are not allowed. Insertion order is not preserved since objects will be inserted based on some sorting technique. Null insertion is not possible in a non-empty TreeSet. We will get NullPointerException if we add. Heterogeneous objects are not allowed.  We will get ClassCastException if we […]