A simple Enum is a list of values that you can select only once at a time. Using your example, size can only be one of S, M, L, etc. For any fabric. You can use simple constants instead of Enum , but this has its advantages of readability, ease of maintenance, and strong type checking.
An EnumSet will be used when you need a variable to accept more than one Enum value at the same time. For example, the font you write on the screen can be bold and italic at the same time. EnumSet allows you to add various values and check whether one of them is set at any given time. If you came to Java from other programming languages, this is a feature commonly called flags .
Compare two:
enum Size { S, M, L, XL, XXL, XXXL } Size currentSize; ... currentSize = Size.S; ... if (currentSize == Size.S) ...
detects, assigns, and then checks a single Enum value.
enum FontStyle { Bold, Italic, Underline, Strikethrough } EnumSet<FontStyle> currentStyle; ... currentStyle = EnumSet.of(FontStyle.Bold, FontStyle.Italic); ... if (currentStyle.contains(FontStyle.Italic)) ...
determines whether it assigns two Enum values at the same time, and then checks whether one of them is actually set.
Gábor Jan 03 '15 at 12:57 2016-01-03 12:57
source share