I have the following example:
import java.util.EnumSet; import java.util.Iterator; public class SizeSet { public static void main(String[] args) { EnumSet largeSize = EnumSet.of(Size.XL,Size.XXL,Size.XXXL); for(Iterator it = largeSize.iterator();it.hasNext();){ Size size = (Size)it.next(); System.out.println(size); } } } enum Size { S, M, L, XL, XXL, XXXL; }
In this code I can understand that the Enum creates an Enum type of Sizes.
My question is: is largeSize
an object of EnumSet type? What does it really mean? I really want to understand it better.
An EnumSet is a specialized Set collection to work with enum classes. It implements the Set interface and extends from AbstractSet: Even though AbstractSet and AbstractCollection provide implementations for almost all the methods of the Set and Collection interfaces, EnumSet overrides most of them.
EnumSet. allOf(Class elementType ) in Java is used to create an enum set that will be used to contain all of the elements in the specified elementType. Syntax: public static > EnumSet allOf(Class elementType )
Use EnumSet. noneOf(Class) to create an empty EnumSet.
As for any variable, its type is found in its declaration:
EnumSet largeSize
So yes, largeSize
(which should be named largeSizes
since it's a collection) is of type EnumSet
. It should also be generified, and thus be declared as
EnumSet<Size> largeSizes
What it means, is that largeSizes
is of type EnumSet
. An EnumSet
is a Set
which contains enum instance of a specific enum type, in a more efficient way than other Set
implementations (like HashSet
, TreeSet
, etc.). To know what an EnumSet
is, read its API.
A simple Enum
is a list of values that you can only select one from at a time. Using your example, a size can be only one of S, M, L, etc for any given cloth. You could use simple constants instead of the Enum
but this has its advantages of readability, easier maintenance and strict type checking.
An EnumSet
will be used when you have the need for a variable to assume more than one Enum
value at the same time. For instance, a font you write to screen with can be both bold and italic at the same time. An EnumSet
will allow you to add the various values and to test whether one of those is actually set at any given time. If you have come to Java from other programming languages, this is the functionality usually called flags.
Compare the two:
enum Size { S, M, L, XL, XXL, XXXL } Size currentSize; ... currentSize = Size.S; ... if (currentSize == Size.S) ...
defines, assigns and then checks for 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)) ...
defines, assigns two Enum
values at the same time, then checks whether one of those is actually set or not.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With