Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does java.util.EnumSet<E> work?

The EnumSet<E> class is defined as:

public abstract class EnumSet<E extends Enum<E>>
extends AbstractSet<E>
implements Cloneable, Serializable

in JCF. Also, most of the methods that the class itself implements are static. Lastly, the class does not seem to implement the add(),iterator(),remove(),size(),contains() or isEmpty() methods and just inherits them from AbstractSet which doesn't implement them. I have two questions:

  1. How exactly EnumSet objects are instantiated and used?
  2. Why can i use the add() method for EnumSet objects?
like image 853
Themistoklis Haris Avatar asked Aug 20 '15 08:08

Themistoklis Haris


People also ask

What is the use of EnumSet in Java?

EnumSet of() Method in Java method in Java is used to create an enum set initially containing the specified elements in the parameters.

What is an EnumSet?

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.

What is EnumSet noneOf?

EnumSet. noneOf(Class elementType ) method in Java is used to create a null set of the type elementType.

How do I create an empty EnumSet?

Use EnumSet. noneOf(Class) to create an empty EnumSet.


2 Answers

Most of the static methods you see are factory methods (of(), complementOf(), allOf(), etc.).

These methods return an instance of EnumSet. The actual type of the EnumSet created and returned by these methods is a subclass of EnumSet (RegularEnumSet, JumboEnumSet), which are not part of the public API, but implement all the required methods. All you need to know is that they implement EnumSet.

like image 183
JB Nizet Avatar answered Oct 01 '22 18:10

JB Nizet


EnumSet is an abstract class itself, so it doesn't have to implement any abstract methods it inherits. It passes that responsibility on to its non-abstract subclasses.

You can call the unimplemented methods because you're actually calling them on an instance of a subclass of EnumSet. (As EnumSet is abstract, it cannot be directly instantiated itself.)

like image 21
daiscog Avatar answered Oct 01 '22 18:10

daiscog