What does EnumSet really mean?

后端 未结 10 1511
小蘑菇
小蘑菇 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条回答
  •  Happy的楠姐
    2020-12-04 16:54

    From Joshua Bloch's book itself and in his own word:

    The java.util package provides EnumSet class to efficiently represent sets of values drawn from a single enum type. This class implements the Set interface, providing all of the richness, type safety and interoperability you get with any other Set implementation. But internally, each EnumSet is represented as a bit vector. If the underlying enum type has sixty-four or fewer elements -- and most do -- the entire EnumSet is represented with a single long, so its performance is comparable to that of a bit field. Bulk operations, such as removeAll and retainAll, are implemented using bit wise arithmetic, just as you'll do manually for bit fields. But you are insulated from the ugliness and error-proneness of manual bit twiddling. The EnumSet does the hard work for you.

    So we can do something like this.

    public class SizeSet {
    
      public enum Size {S, M, L, XL, XXL, XXXL}
    
      public void applySize(Set sizes){}
    
    }
    

    Client Code calling it might do something like

    SizeSet largeSizeSet = new SizeSet();
    largeSizeSet.applySize(EnumSet.of(Size.L, Size.XXL, Size.XXL));
    

    Note that the applySize method takes the Set rather than an EnumSet. While it is pretty obvious and likely that the client would pass an EnumSet to the method, it is a good practice to accept an interface rather than the concrete implementation.

提交回复
热议问题