HashSet VS TreeSet Java: In this article, we will compare important implementation classes of Set i.e.; HashSet v/s LinkedHashSet v/s TreeSet
So lets us discuss in tabular format;
HashSet VS TreeSet VS LinkedHashSet In Java
HashSet | LinkedHashSet | TreeSet |
Uses a hash table to store element/objects where duplicates are NOT allowed | Uses a combination of (hash table + LinkedList) to store element/objects where duplicates are NOT allowed | Uses the balanced tree to store element/objects where duplicates are NOT allowed |
Insertion order is not maintained, as it uses a hashing technique to store element/objects | Insertion order is maintained, as it uses the doubly-linked list to store element/objects | Insertion order is not maintained, as element/objects are stored according to some sorting order |
HashSet doesn’t deal with sorting order, but it can be converted to TreeSet to store element/objects in some sorting orderTreeSet ts = new TreeSet(HashSet); | LinkedHashSet doesn’t deal with sorting order; but it can be converted to TreeSet to store element/objects in some sorting orderTreeSet ts = new TreeSet(linkedHashSet); | Element/objects stored in TreeSet are according to some sorting order; it could be either default natural sorting order or programmer-defined customized sorting order |
While iterating HashSet, we will get items in random order | While iterating LinkedHashSet, we will get items as per insertion order | While iterating TreeSet, we will get items in sorted order; either natural ordering or customized sorting order |
This is introduced in the original collection framework in Java 1.2 version | This is introduced in Java 1.4version | This is also introduced in the original collection framework in Java 1.2 version |
Allows NULL insertion but a maximum of only one NULL value | Allows NULL insertion but a maximum of only one NULL value | From Java 1.7 version, NULL is not allowed to insert; But with Java version less than 1.6, only as 1st element allowed |
Factors to consider while discussing any collection class
We should consider factors while discussing any implementation class of collection framework or for that matter Map interface,
- Underlying data structure
- Duplicates are allowed or Not
- Insertion order is maintained or Not
- Whether NULL insertion is possible or Not
- If possible, how many NULL values can be inserted
- Whether collection class provide sorting, by default
- Is there any way to apply customized sorting
- Performance, while dealing with retrieval or manipulation (addition/deletion)
- By default, all methods are synchronized or Not
If you want to More About the HashSet VS TreeSet topic then you can write to us at admin@softwaretestingo.com