Java Collections – EnumSet Example

A specialized Map implementation for use with enum type keys. All of the keys in an EnumSet must come from a single enum type that is specified when the map is created. EnumSets are represented internally as arrays. It is for this reason that they are extremely compact and efficient. In my example, you can see the Enums in the Mercedes class detailed below.

Big-O Notation

Besides being extremely compact and efficient, this implementation provides constant-time O(1) performance for the basic operations add(), contains() and next().

Creating an EnumSet — Wrong Way

The EnumSet class works differently than all other classes in the collections framework in that it does not have a public constructor. So you may not instantiate an EnumSet the way that other classes are typically done.

Please Note

EnumSet wrongSet = new EnumSet(); // This will NOT work!

Creating an EnumSet — Correct Way

It uses a Factory design pattern for the creation of EnumSet. You must use one the static methods provided for you to do this.

Set<Mercedes> mercedes_full = EnumSet.allOf(Mercedes.class);
Set<Mercedes> mercedes_economy = EnumSet.of(Mercedes.CLA_SEDAN, 
                                Mercedes.C_SEDAN, Mercedes.CLA_COUPE, 
                                Mercedes.C_COUPE,Mercedes.GLA_SUV, 
                                Mercedes.GLK_SUV);
Set<Mercedes> mercedes_practical = EnumSet.of(Mercedes.E_SEDAN, 
                                Mercedes.E_COUPE, Mercedes.CLS_COUPE, 
                                Mercedes.M_SUV, Mercedes.E_WAGON, 
                                Mercedes.GL_SUV, Mercedes.SLK_ROADSTER);
Set<Mercedes> mercedes_luxury = EnumSet.of(Mercedes.S_SEDAN, 
                                Mercedes.S_COUPE, Mercedes.SLS_COUPE, 
                                Mercedes.G_SUV, Mercedes.E_CABRIOLET, 
                                Mercedes.SL_ROADSTER, Mercedes.SLS_ROADSTER);

Factory Creation Methods

Method/TypeDescription
allOf(Class ElemType)This method creates an enum set containing all of the elements in the specified element type.
of(Enum e)This method creates an enum set initially containing the specified element.
of(Enum e1, Enum e2)This method creates an enum set initially containing the specified elements.
of(Enum e1, Enum e2, Elem e3)This method creates an enum set initially containing the specified elements.
of(Enum e1, Enum e2, Elem e3, Elem e4)This method creates an enum set initially containing the specified elements.
of(Enum e1, Enum e2, Elem e3, Elem e4, Elem e5)This method creates an enum set initially containing the specified elements.
of(Enum first, .. Enum last)This method creates an enum set initially containing the specified elements.
range(Enum fromElem, Enum toElem)This method creates an enum set initially containing all of the elements in the range defined by the two specified endpoints.
copyOf(EnumSet s)This method creates an enum set initialized from the specified collection.
complimentOf(EnumSet s)This method creates an enum set with the same element type as the specified enum set, initially containing all the elements of this type that are not contained in the specified set.

EnumSet Rules

  • An EnumSet can only store Enum constants
  • You may NOT store nulls. Doing will result in a NullPointerException
  • An EnumSet can only store Enums from a single Enum type
  • When iterating you will be guaranteed the same order
  • EnumSets are not thread safe, you may need to wrap in Collections.synchronizedSet()

Adding elements

You may add elements to the sedans_coupes EnumSet by using the add(Enum) method. EnumSets can only use Enums as their elements, no other types may be used.

// New Set composed of Sedans and Coupes Only using Range
Set  sedans_coupes = EnumSet.range(Mercedes.CLA_SEDAN, Mercedes.SLS_COUPE);
sedans_coupes.add(Mercedes.E_CABRIOLET);
...

Removing elements

Removes the mapping for this key from this map, if present. Removing elements is just a matter of calling the remove(Enum) method.

// Remove an element from the full lineup enumset
mercedes_full.remove(Mercedes.C_SEDAN);

Size of Collection

Returning the number of elements in a EnumSet is as easy as calling the size() method.

mercedes_full.size();

Iterating through the Collection using Iterator

// Loop through the collection of cars using iterator
Iterator<Mercedes> iter = mercedes_full.iterator();
while (iter.hasNext()) {
  Mercedes c = iter.next();
  System.out.println(c);
}

Iterating through the Collection

Java 1.5 and above provides a foreach loop, which makes it much easier to iterate over the entire collection. This is my preferred way of doing it.

// Iterate through the entire EnumSet using foreach
for (Mercedes c : mercedes_full) {
   System.out.println(c);
}

Full Program Listing

package com.avaldes.tutorials;

import java.util.EnumSet;
import java.util.Set;

public class EnumSetExample {

  private enum Mercedes {CLA_SEDAN,  C_SEDAN, E_SEDAN, S_SEDAN, 
               CLA_COUPE,  C_COUPE, E_COUPE, CLS_COUPE, S_COUPE, SLS_COUPE,
               GLA_SUV,  GLK_SUV, M_SUV, GL_SUV, G_SUV, E_WAGON,
               E_CABRIOLET,  SLK_ROADSTER, SL_ROADSTER, SLS_ROADSTER
  };
  
  public static void main(String[] args) {
    Set<Mercedes> mercedes_full = EnumSet.allOf(Mercedes.class);
    
    Set<Mercedes> mercedes_economy = EnumSet.of(Mercedes.CLA_SEDAN, Mercedes.C_SEDAN, 
                          Mercedes.CLA_COUPE, Mercedes.C_COUPE,
                          Mercedes.GLA_SUV, Mercedes.GLK_SUV);
    
    Set<Mercedes> mercedes_practical = EnumSet.of(Mercedes.E_SEDAN, Mercedes.E_COUPE, Mercedes.CLS_COUPE, 
                          Mercedes.M_SUV, Mercedes.E_WAGON, Mercedes.GL_SUV, Mercedes.SLK_ROADSTER);
    
    Set<Mercedes> mercedes_luxury = EnumSet.of(Mercedes.S_SEDAN, Mercedes.S_COUPE, Mercedes.SLS_COUPE,
                          Mercedes.G_SUV, Mercedes.E_CABRIOLET, Mercedes.SL_ROADSTER, Mercedes.SLS_ROADSTER);
    
    // print the full lineup of all Mercedes-Benz cars
    System.out.println("Mercedes Full Inventory:" + mercedes_full);
    System.out.println("Mercedes Full Lineup Contains: " + mercedes_full.size() + " cars...");

    // print the economy class of cars (Less than $40k USD) 
    System.out.println("nMercedes Economy Set...:" + mercedes_economy);
    System.out.println("Mercedes Economy Lineup Contains: " + mercedes_economy.size() + " cars...");
      

    // print the mid-range class of cars ($40k ~ $70k USD) 
    System.out.println("nMercedes Practical Set.:" + mercedes_practical);
    System.out.println("Mercedes Practical Lineup Contains: " + mercedes_practical.size() + " cars...");
      
    // print luxury class of cars (Greater than $70k USD) 
    System.out.println("nMercedes Luxury Set....:" + mercedes_luxury);
    System.out.println("Mercedes Luxury Lineup Contains: " + mercedes_luxury.size() + " cars...");
      
    // New Set composed of Sedans and Coupes Only using Range
    Set <Mercedes> sedans_coupes = EnumSet.range(Mercedes.CLA_SEDAN, Mercedes.SLS_COUPE);
    System.out.println("nMercedes Sedans & Coupes.....:" + sedans_coupes);
    System.out.println("Mercedes Luxury Lineup Contains: " + sedans_coupes.size() + " cars...");
      
    // Iterate through the entire EnumSet
    System.out.println("nDisplaying the full list of cars...");
    for (Mercedes c : mercedes_full) {
      System.out.println(c); 
    }
  }
}

Output

Mercedes Full Inventory:[CLA_SEDAN, C_SEDAN, E_SEDAN, S_SEDAN, CLA_COUPE, C_COUPE, E_COUPE, CLS_COUPE, S_COUPE, SLS_COUPE, GLA_SUV, GLK_SUV, M_SUV, GL_SUV, G_SUV, E_WAGON, E_CABRIOLET, SLK_ROADSTER, SL_ROADSTER, SLS_ROADSTER]
Mercedes Full Lineup Contains: 20 cars...

Mercedes Economy Set...:[CLA_SEDAN, C_SEDAN, CLA_COUPE, C_COUPE, GLA_SUV, GLK_SUV]
Mercedes Economy Lineup Contains: 6 cars...

Mercedes Practical Set.:[E_SEDAN, E_COUPE, CLS_COUPE, M_SUV, GL_SUV, E_WAGON, SLK_ROADSTER]
Mercedes Practical Lineup Contains: 7 cars...

Mercedes Luxury Set....:[S_SEDAN, S_COUPE, SLS_COUPE, G_SUV, E_CABRIOLET, SL_ROADSTER, SLS_ROADSTER]
Mercedes Luxury Lineup Contains: 7 cars...

Mercedes Sedans & Coupes.....:[CLA_SEDAN, C_SEDAN, E_SEDAN, S_SEDAN, CLA_COUPE, C_COUPE, E_COUPE, CLS_COUPE, S_COUPE, SLS_COUPE]
Mercedes Luxury Lineup Contains: 10 cars...

Displaying the full list of cars...
CLA_SEDAN
C_SEDAN
E_SEDAN
S_SEDAN
CLA_COUPE
C_COUPE
E_COUPE
CLS_COUPE
S_COUPE
SLS_COUPE
GLA_SUV
GLK_SUV
M_SUV
GL_SUV
G_SUV
E_WAGON
E_CABRIOLET
SLK_ROADSTER
SL_ROADSTER
SLS_ROADSTER

Other Related Posts

Map Examples

List Examples

Set Examples

Please Share Us on Social Media

Facebooktwittergoogle_plusredditpinterestlinkedinmail

Leave a Reply

Your email address will not be published. Required fields are marked *