HashSet vs TreeSet in java

In Java, Set is an interface that has many implementations. HashSet and TreeSet are two of the most commonly used Set implementations. The primary difference between them is their internal implementation, ordering, null objects, and comparison.

HashSet is implemented using a hash table, which makes it faster than TreeSet for search, insert, and delete operations. However, it does not maintain any ordering of the elements. On the other hand, TreeSet uses a self-balancing binary search tree, which makes it slower but keeps the elements sorted. TreeSet also has additional methods to deal with the ordered set, like first(), last(), headSet(), and tailSet(). One disadvantage of TreeSet is that it doesn't allow null objects and throws a NullPointerException if you try to add one.

To illustrate, suppose we have a Set of strings. If we add "dog", "cat", "fish", and "bird" to HashSet, they will be stored in any order. But if we add them to TreeSet, they will be sorted in ascending order.

HashSet allows null objects, but TreeSet does not. For example, if we try to add a null object to a TreeSet, it will throw a NullPointerException.

If we need to frequently perform read/write operations, TreeSet is a better choice. But if we want unique elements without any particular order, HashSet is better.

To summarize, HashSet and TreeSet are two different Set implementations with their unique features. HashSet is faster and allows null objects, while TreeSet maintains elements sorted in ascending order but doesn't allow null objects.

Here are some examples of how to use HashSet and TreeSet in Java:

Example 1: HashSet

csharp
import java.util.HashSet; class Example { public static void main(String[] args) { HashSet<String> set = new HashSet<String>(); set.add("dog"); set.add("cat"); set.add("fish"); set.add("bird"); set.add(null); // allow null for (String s : set) { System.out.println(s); } } }

Output:

javascript
null fish bird cat dog

Example 2: TreeSet

csharp
import java.util.TreeSet; class Example { public static void main(String[] args) { TreeSet<String> set = new TreeSet<String>(); set.add("dog"); set.add("cat"); set.add("fish"); set.add("bird"); for (String s : set) { System.out.println(s); } } }

Output:

bash
bird cat dog fish
Previous Post Next Post