Stopping repetition in Java enums

后端 未结 4 1555
梦谈多话
梦谈多话 2020-12-03 16:26

I have the following enum in a Java class:

public enum Resolution {
    RES_32 (32),
    RES_64 (64);
    private final int asInt;
    private R         


        
4条回答
  •  萌比男神i
    2020-12-03 17:10

    EnumSet may be helpful in this context. Given the following,

    public enum Resolution {
    
        RES_32(32),
        RES_64(64),
        RES_128(128),
        RES_256(256);
    
        public static Set deluxe = EnumSet.allOf(Resolution.class);
        public static Set typical = EnumSet.range(RES_64, RES_128);
        public static Set ecomomy = EnumSet.of(RES_32);
    
        private final int asInt;
    
        private Resolution(int asInt) {
            this.asInt = asInt;
        }
    };
    

    Suitably named sets may be used as shown below.

    for (Resolution r : Resolution.deluxe) {
        System.out.println(r.asInt);
    }
    

提交回复
热议问题