Java: Enum vs. Int

前端 未结 9 2261
野的像风
野的像风 2020-11-27 14:11

When using flags in Java, I have seen two main approaches. One uses int values and a line of if-else statements. The other is to use enums and case-switch statements.

<
相关标签:
9条回答
  • 2020-11-27 14:51

    Even though this question is old, I'd like to point out what you can't do with ints

    public interface AttributeProcessor {
        public void process(AttributeLexer attributeLexer, char c);
    }
    
    public enum ParseArrayEnd implements AttributeProcessor {
        State1{
            public void process(AttributeLexer attributeLexer, char c) {
                .....}},
        State2{
            public void process(AttributeLexer attributeLexer, char c) {
                .....}}
    }
    

    And what you can do is make a map of what value is expected as a Key, and the enum as a value,

    Map<String, AttributeProcessor> map 
    map.getOrDefault(key, ParseArrayEnd.State1).process(this, c);
    
    0 讨论(0)
  • 2020-11-27 14:52

    You may even use Enums to replace those bitwise combined flags like int flags = FLAG_1 | FLAG_2;

    Instead you can use a typesafe EnumSet:

    Set<FlagEnum> flags = EnumSet.of(FlagEnum.FLAG_1, FlagEnum.FLAG_2);
    
    // then simply test with contains()
    if(flags.contains(FlagEnum.FLAG_1)) ...
    

    The documentation states that those classes are internally optimized as bit vectors and that the implementation should be perform well enough to replace the int-based flags.

    0 讨论(0)
  • 2020-11-27 14:58

    Answer to your question: No, the after a negligible time to load the Enum Class, the performance is the same.

    As others have stated both types can be used in switch or if else statements. Also, as others have stated, you should favor Enums over int flags, because they were designed to replace that pattern and they provide added safety.

    HOWEVER, there is a better pattern that you consider. Providing whatever value your switch statement/if statement was supposed to produce as property.

    Look at this link: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html Notice the pattern provided for giving the planets masses and radii. Providing the property in this manner insures that you won't forget to cover a case if you add an enum.

    0 讨论(0)
提交回复
热议问题