Java: Enum vs. Int

前端 未结 9 2301
野的像风
野的像风 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: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.

提交回复
热议问题