EnumSet vs HashSet in Java

1. Introduction

In Java, EnumSet and HashSet are two distinct implementations of the Set interface. EnumSet is a specialized Set implementation for use with enum types, offering a highly efficient way to maintain sets of enums. Conversely, HashSet is a general-purpose Set implementation based on a hash table, capable of storing any kind of object.

2. Key Points

1. EnumSet is designed specifically for use with enum types, providing a highly efficient bit-vector representation of the set.

2. HashSet can store any type of object and uses a hash table to maintain its elements.

3. EnumSet does not allow null elements, while HashSet does.

4. EnumSet offers superior performance for certain operations compared to HashSet, particularly when the universe of enum instances is small.

3. Differences

EnumSet HashSet
Only for enum types. Can hold any Object type.
Does not permit null elements. Allows one null element.
Performance is highly optimized for enums. Good general-purpose performance, not optimized for enums.
Internally represented as a bit-vector. Based on a hash table implementation.

4. Example


// Import the necessary classes
import java.util.EnumSet;
import java.util.HashSet;
import java.util.Set;

// An enumeration of example colors
enum Color {
    RED, GREEN, BLUE
}

public class SetComparison {
    public static void main(String[] args) {
        // Step 1: Create an EnumSet containing all constants of the enum Color
        Set<Color> enumSet = EnumSet.allOf(Color.class);

        // Step 2: Create a HashSet
        Set<Color> hashSet = new HashSet<>();

        // Step 3: Add elements to the HashSet
        hashSet.add(Color.RED);
        hashSet.add(Color.GREEN);
        hashSet.add(Color.BLUE);

        // Step 4: Print both sets
        System.out.println("EnumSet: " + enumSet);
        System.out.println("HashSet: " + hashSet);
    }
}

Output:

EnumSet: [RED, GREEN, BLUE]
HashSet: [RED, GREEN, BLUE]

Explanation:

1. EnumSet is created using EnumSet.allOf(Color.class), which initializes the set with all the enum constants defined in the Color enum.

2. A HashSet is instantiated and populated with Color enum instances, similar to the EnumSet.

3. Both sets are printed, showing that they contain identical elements, demonstrating the similar behavior of EnumSet and HashSet in this context.

5. When to use?

- Use EnumSet when you're working exclusively with enum types and require efficient operations for sets of enums.

- Opt for HashSet when you need a set implementation to work with any objects and when the key's hash codes are well-distributed.

Comments