When to use Enum or Collection in Java

前端 未结 6 1710
醉梦人生
醉梦人生 2020-12-14 02:03

Under what circumstances is an enum more appropriate than, for example, a Collection that guarantees unique elements (an implementer of java.util.Set, I guess...)?

(

相关标签:
6条回答
  • 2020-12-14 02:11

    Basically when it's a well-defined, fixed set of values which are known at compile-time.

    You can use an enum as a set very easily (with EnumSet) and it allows you to define behaviour, reference the elements by name, switch on them etc.

    0 讨论(0)
  • 2020-12-14 02:23

    When the elements are known up front and won't change, an enum is appropriate.

    If the elements can change during runtime, use a Set.

    0 讨论(0)
  • 2020-12-14 02:29

    Note: you can have both with an EnumSet.

    0 讨论(0)
  • 2020-12-14 02:30

    Great responses - I'll try and summarise, if just for my own reference - it kinda looks like you should use enums in two situations:

    All the values you need are known at compile time, and either or both of the following:

    • you want better performance than your usual collection implementations
    • you want to limit the potential values to those specified at compile time

    With the Collection over enumeration links that Jon gave, you can get the benefits of enum performance and safety as an implementation detail without incorporating it into your overall design.

    Community wiki'd, please do edit and improve if you want to!

    0 讨论(0)
  • 2020-12-14 02:35

    I am no java guru, but my guess is to use enumeration when you want to gurantee a certain pool of values, and to use a collection when you want to gurantee uniqueness. Example would be to enumerate days of the week (cant have "funday") and to have a collection of SSN (generic example i know!)

    0 讨论(0)
  • 2020-12-14 02:36

    In some situations your business requires the creation of new items, but at the same time business logic based on some fixed items. For the fixed ones you want an enum, the new ones obviously require some kind of collection/db.

    I've seen projects using a collection for this kind of items, resulting in business logic depending on data which can be deleted by the user. Never do this, but do create a separate enum for the fixed ones and a collection for the others, just as required.

    An other solution is to use a collection with immutable objects for the fixed values. These items could also reside in a db, but have an extra flag so users cannot update / delete it.

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