HashMap vs TreeMap vs LinkedHashMap in Java | Java @ Desk
Home » , » HashMap vs TreeMap vs LinkedHashMap in Java

HashMap vs TreeMap vs LinkedHashMap in Java

HashMap vs TreeMap vs LinkedHashMap in Java

java.util.HashMap, java.util.LinkedHashMap, java.util.TreeMap implements the Map interface in Java. All 3 implementation fulfill the basic principal of a Map interface by not allowing duplicates keys. The put() method returns a boolean. In case of duplicate entry, the add() method returns false.

Difference between the three :

1) Sorting and Ordering of Elements

HashMap does not maintains any order of elements. Every time a new element is added, the order of elements may or may not be changed. LinkedHashMap strictly maintains inserion order of elements. TreeSet also does not maintains insertion order, it sorts the element and maintain sorting order

HashMap -> Does not maintain insertion order
LinkedHashMap -> Maintains insertion order
TreeMap -> Does not maintain insertion order as it sorts the elements inserted based on keys.

2) Null Elements
HashMap -> Allow 1 Null Key
LinkedHashMap -> Allow 1 Null Key
TreeMap -> Does not Allow Null Key. Throws RuntimeException (NullPointerException).





0 comments:

Post a Comment