What are enums and why are they useful?

后端 未结 27 1314
一整个雨季
一整个雨季 2020-11-22 07:06

Today I was browsing through some questions on this site and I found a mention of an enum being used in singleton pattern about purported thread safety benefits

27条回答
  •  感情败类
    2020-11-22 07:28

    Use enums for TYPE SAFETY, this is a language feature so you will usually get:

    • Compiler support (immediately see type issues)
    • Tool support in IDEs (auto-completion in switch case, missing cases, force default, ...)
    • In some cases enum performance is also great (EnumSet, typesafe alternative to traditional int-based "bit flags.")

    Enums can have methods, constructors, you can even use enums inside enums and combine enums with interfaces.

    Think of enums as types to replace a well defined set of int constants (which Java 'inherited' from C/C++) and in some cases to replace bit flags.

    The book Effective Java 2nd Edition has a whole chapter about them and goes into more details. Also see this Stack Overflow post.

提交回复
热议问题