Last Updated: 22 January, 2023
LinkedHashSet and TreeSet both implement the Set interface in Java and are available in the java.util package.
There are many differences between the LinkedHashSet and TreeSet that are given below.
The LinkedHashSet class of the Java collections framework was introduced in the JDK 1.4 version and is available in the java.util package.
LinkedHashSet is the Hashtable and linked list implementation of the Set interface with preserved iteration order. The linked list defines the iteration order, which is the order in which elements are inserted into the set. Insertion order is not affected if an element is re-inserted into the set.
LinkedHashSet is a child class of HashSet, so it has all the functionalities of the HashSet class. The HashSet does not maintain the insertion order of elements, whereas the LinkedHashSet maintains the element insertion order. This one is the main difference between both.
Java LinkedHashSet Class Declaration
Here, E defines the type of elements that the Set will contain.
Java LinkedHashSet important features:
The TreeSet class of the Java collections framework was introduced in the JDK 1.2 version and is available in the java.util package.
A TreeSet is a sorted collection of objects. A TreeSet is the implementation of the SortedSet interface in Java that uses a tree for storage. The ordering of the elements is maintained by a set using their natural (ascending) order.
TreeSet provides fast access and retrieval operations, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly.
Java TreeSet Class Declaration
Here, E defines the type of elements that the Set will contain.
Java TreeSet important features:
LinkedHashSet and TreeSet have many differences. Let's understand with the help of the given table.
LinkedHashSet | TreeSet |
---|---|
The underlying data structure is a hash table + linked list (doubly linked list). | The underlying data structure of the TreeSet is the Balanced Tree. |
Preserve the iteration order (ordered set). | Store the elements in a sorted order (default, in ascending order). |
Introduced in the JDK 1.4 version. | Introduced in the JDK 1.2 version. |
Allows to insert null value. | Does not allow to insert null. |
Output
LinkedHashSet elements: [800, 500, null, 200]
Output
[10, 20, 30, 40, 50]
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com