What does EnumSet really mean?

后端 未结 10 1502
小蘑菇
小蘑菇 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:44

    Simplifying your code

    EnumSet largeSize = EnumSet.of(Size.XXXL, Size.XXL, Size.XL, Size.L);
    for(Size size: largeSize)
        System.out.print(size+" ");
    

    You can see that largeSize is a regular Set except its designed to store Enums. How is that different? Firstly the JVM knows all the possible values of the set which means instead of storing all the objects it can use a bitmap where 1 means the item is present and 0 means it is not. This also means the order of the set is the order of the ordinal values i.e. the order they were defined. This is why this prints

    L XL XXL XXXL
    

    If you want to know more detail I suggest you read the source for this class.

提交回复
热议问题