Difference Between EnumSet and TreeSet in Java


In Java, collections provide a wide range of options for storing and manipulating data. Two popular collection classes, EnumSet and TreeSet, offer distinct approaches for managing sets of elements. While they both serve the purpose of storing unique elements, they have fundamental differences in their implementation and usage. This article aims to delve into these dissimilarities, providing a clear understanding of EnumSet and TreeSet in Java.

Syntax

Before we investigate their contrasts, let's look at the fundamental language structure for making EnumSet and TreeSet occurrences −

EnumSet

EnumSet<EnumType> enumSet = EnumSet.noneOf(EnumType.class);

TreeSet

TreeSet<DataType> treeSet = new TreeSet<>();

Explanation of Syntax

EnumSet is designed specifically to work with enumeration types in Java. It utilizes the EnumType class, which represents the specific enumeration type you want to create a set for. By calling the "noneOf" strategy on EnumSet and giving the EnumType course, an purge EnumSet occasion is made.

TreeSet, on the other hand, may be a general-purpose set execution that can store any sort of objects. In this case, we announce a TreeSet question called "treeSet" utilizing the generic sentence structure, permitting us to characterize the particular information the set will contain.

Approach 1: EnumSet

EnumSet provides a memory-efficient representation of sets containing enum values. It internally represents sets as bit vectors, which makes operations like union, intersection, and complement very efficient. Here's an algorithmic representation of

Approach 1

  • Create an EnumSet instance for the desired enumeration type.

  • Add elements to the EnumSet using the "add" method or by passing multiple enum constants during initialization.

  • Perform set operations such as union, intersection, or complement using EnumSet methods.

  • Iterate over the elements using the enhanced for loop or other iterating techniques.

  • Perform additional operations specific to EnumSet, such as checking if the set is empty or obtaining its size.

Example

import java.util.EnumSet;

enum Days {
   MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
}

public class EnumSetExample {
   public static void main(String[] args) {
      EnumSet<Days> workingDays = EnumSet.of(Days.MONDAY, Days.TUESDAY, Days.WEDNESDAY, Days.THURSDAY, Days.FRIDAY);
      EnumSet<Days> weekendDays = EnumSet.complementOf(workingDays);
    
      System.out.println("Working days: " + workingDays);
      System.out.println("Weekend days: " + weekendDays);
    
      for (Days day : workingDays) {
         System.out.println("Today is a working day: " + day);
      }
   }
}

Output

Working days: [MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY]
Weekend days: []
Today is a working day: MONDAY
Today is a working day: TUESDAY
Today is a working day: WEDNESDAY
Today is a working day: THURSDAY
Today is a working day: FRIDAY

Explanation of the Code in Approach 1

In this code snippet, we define an enumeration type called "Days" representing the days of the week. We create an EnumSet named "workingDays" and initialize it with Monday to Friday using the "of" method. We then obtain the "weekendDays" set by taking the complement of the "workingDays" set. Finally, we iterate over the "workingDays" set and print each day using an enhanced for loop.

Approach 2: TreeSet

TreeSet, as the name suggests, is implemented using a balanced tree structure. It offers guaranteed logarithmic time cost for basic operations like add, remove, and contains. Here's an algorithmic representation of

Approach 2

  • Create a TreeSet instance, specifying the desired data type (such as Integer, String, or a custom object) using the generic syntax.

  • Add elements to the TreeSet using the "add" method.

  • Remove elements from the TreeSet using the "remove" method.

  • Check if an element exists in the TreeSet using the "contains" method.

  • Iterate over the elements using the iterator or enhanced for loop.

  • Perform additional operations provided by the TreeSet class, such as getting the first or last element, or obtaining a subset of the set.

Example

import java.util.TreeSet;

public class TreeSetExample {
   public static void main(String[] args) {
      TreeSet<Integer> numbers = new TreeSet<>();
    
      numbers.add(5);
      numbers.add(2);
      numbers.add(8);
      numbers.add(1);
      numbers.add(4);
    
      numbers.remove(2);
    
      System.out.println("Numbers: " + numbers);
    
      System.out.println("Contains 4? " + numbers.contains(4));
    
      for (int number : numbers) {
         System.out.println("Number: " + number);
      }
   }
}

Output

Numbers: [1, 4, 5, 8]
Contains 4? true
Number: 1
Number: 4
Number: 5
Number: 8

Explanation of the Code in Approach 2

In this code scrap, we make a TreeSet named "numbers" that stores integrability. We include a few numbers utilizing the "include" strategy and evacuate the number 2 utilizing the "evacuate" strategy. We at that point check in the event that the set contains the number 4 utilizing the "contains" strategy. Finally, we iterate over the TreeSet and print each number using an enhanced for loop.

Difference Between EnumSet and TreeSet in Java

Feature

EnumSet

TreeSet

Purpose

Designed specifically for working with enumeration types

A general-purpose set implementation

Implementation

Uses bit vectors internally for memory efficiency

Based on a balanced tree structure

Type of Elements

Limited to enumeration types

Can store any type of objects

Performance

Efficient for operations like union, intersection, and complement

Guaranteed logarithmic time cost for basic operations

Ordering

Follows the natural order of enum constants

Maintains elements in sorted order (natural or custom)

Conclusion

In conclusion, EnumSet and TreeSet are two distinct implementations of the Set interface in Java. EnumSet is specifically designed for working with enumeration types and provides efficient operations using bit vectors. On the other hand, TreeSet is a general-purpose set implementation based on a balanced tree structure, offering guaranteed logarithmic time complexity for essential operations. Choosing between EnumSet and TreeSet depends on the specific requirements of your application. By understanding their differences and capabilities, you can make an informed decision and leverage the most suitable set implementation for your Java projects.

Updated on: 28-Jul-2023

45 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements