Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42710

Why EnumSet is implemented as abstract class and EnumMap is implemented as concrete class?

I was wondering, is there any reason why EnumSet is implemented as abstract class and EnumMap is implemented as concrete class?

Upvotes: 24

Views: 1925

Answers (2)

axtavt
axtavt

Reputation: 242696

EnumSet actually has two implementations - one for enums with 64 or less elements (flags indicating presence of values in the set are stored as long) and another one for other enums (flags are stored as long[]). Factory methods of EnumSet return one of them depending on the enum class passed in.

Such an optimization doesn't make sense for EnumMap (since array to store values is needed anyways), therefore EnumMap is a concrete class.

Upvotes: 26

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298898

EnumSet uses two implementations, RegularEnumSet and JumboEnumSet, depending on the size of your enum (64 elements being the threshold). The factory methods delegate to the appropriate implementation.

EnumMap on the other hand works the same for all enum types (it keeps an array of all enum items and an equally-sized array of values), so there's no need for an abstract class.

Upvotes: 7

Related Questions