WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Java Collections · Advanced · question 45 of 100

What is the difference between a HashSet and a TreeSet in terms of performance and usage?

📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

HashSet and TreeSet are two implementations of the Set interface in Java Collections. The main differences between the two are related to their implementation and performance characteristics.

HashSet is implemented as a hash table, which means that it uses a hash function to compute an index into an array of buckets or slots, where each bucket can store multiple elements. When an element is added to the set, its hash code is computed and used to determine the appropriate bucket for the element. If the bucket is empty, the element is simply added to the bucket. If the bucket already contains one or more elements, then the element is added to the bucket and a linear search is performed to check if the element is already in the bucket. If the element is already in the bucket, it is not added again.

TreeSet, on the other hand, is implemented as a tree structure, specifically a self-balancing binary search tree. This means that elements are stored in a sorted order, and operations like add, remove, and contains take O(log n) time complexity. The order of elements is determined either by their natural ordering (as defined by the Comparable interface) or by a Comparator passed to the constructor of the TreeSet.

In terms of performance, HashSet is generally faster than TreeSet for most operations, especially for large collections. This is because hash tables have an average O(1) time complexity for add, remove, and contains operations. However, HashSet does not guarantee any specific order of its elements.

TreeSet, on the other hand, guarantees that its elements are stored in a sorted order, which can be useful in some scenarios. It is also more efficient than a regular sorted List, as it can perform operations like add, remove, and contains in O(log n) time complexity. However, its performance can degrade if the tree becomes unbalanced, which can happen if the elements are not uniformly distributed.

Here is an example code snippet that demonstrates the differences between HashSet and TreeSet:

import java.util.HashSet;
import java.util.TreeSet;

public class SetExample {
    public static void main(String[] args) {
        HashSet<Integer> hashSet = new HashSet<>();
        hashSet.add(3);
        hashSet.add(1);
        hashSet.add(2);
        hashSet.add(5);
        hashSet.add(4);
        System.out.println("HashSet: " + hashSet);
    
        TreeSet<Integer> treeSet = new TreeSet<>();
        treeSet.add(3);
        treeSet.add(1);
        treeSet.add(2);
        treeSet.add(5);
        treeSet.add(4);
        System.out.println("TreeSet: " + treeSet);
    }
}

Output:

HashSet: [1, 2, 3, 4, 5]
TreeSet: [1, 2, 3, 4, 5]

In this example, we create a HashSet and a TreeSet, and add the same elements to both sets. When we print out the contents of the two sets, we can see that they both contain the same elements, but the order is different. This is because HashSet does not guarantee any specific order, while TreeSet sorts its elements.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Java Collections interview — then scores it.
📞 Practice Java Collections — free 15 min
📕 Buy this interview preparation book: 100 Java Collections questions & answers — PDF + EPUB for $5

All 100 Java Collections questions · All topics