What does EnumSet really mean?

后端 未结 10 1514
小蘑菇
小蘑菇 2020-12-04 16:08

I have the following example:

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

public class SizeSet {

    public static void main(String[] args) {
             


        
10条回答
  •  日久生厌
    2020-12-04 16:54

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

    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

    Check out this article to learn more about EnumSet.

提交回复
热议问题