Enum values().length vs private field

后端 未结 4 1692
伪装坚强ぢ
伪装坚强ぢ 2020-12-08 13:12

I have enumeration like this:

public enum Configuration {
    XML(1),
    XSLT(10),
    TXT(100),
    HTML(2),
    DB(20);

    private final int id;
    pri         


        
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-08 13:36

    Another approach is to use a constant initialized on top of the values() method.

    public enum Colors {
        BLUE, GREEN, FUCHSIA;
        public static int length = Colors.values().length;
    }
    

    This way you have an automatically updated constant and still avoid that "values()" overhead.

提交回复
热议问题