What does EnumSet really mean?

Viewed 63306

I have the following example:

import java.util.EnumSet;
import java.util.Iterator;

public class SizeSet {

    public static void main(String[] args) {
        EnumSet largeSize = EnumSet.of(Size.XL,Size.XXL,Size.XXXL);
        for(Iterator it = largeSize.iterator();it.hasNext();){
            Size size = (Size)it.next();
            System.out.println(size);
        }
    }
}


enum Size {
  S, M, L, XL, XXL, XXXL;

}

In this code I can understand that the Enum creates an Enum type of Sizes.

My question is: is largeSize an object of EnumSet type? What does it really mean? I really want to understand it better.

10 Answers

An EnumSet is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet:

enter image description here

When you plan to use an EnumSet youhave to take into consideration some points:

  1. It can contain only enum values and all the values have to belong to the same enum
  2. It doesn’t allow to add null values, throwing a NullPointerException in an attempt to do so
  3. It’s not thread-safe, so we need to synchronize it externally if required
  4. The elements are stored following the order in which they are declared in the enum
  5. It uses a fail-safe iterator that works on a copy, so it won’t throw a ConcurrentModificationException if the collection is modified when iterating over it

Now, the EnumSet largeSize part is a variable declaration so yes, it's of type EnumSet. Please notice that you can add the type of elements in the collection for better type safety: EnumSet<Size>

Check out this article to learn more about EnumSet.

Related