When to use Enum or Collection in Java

前端 未结 6 1702
醉梦人生
醉梦人生 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: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!

提交回复
热议问题