You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中哪个类实现抽象类EnumSet?实例创建疑问

Answers to Your EnumSet Questions

1. Which class implements the abstract EnumSet class in Java?

Great question! EnumSet actually has two package-private concrete implementations hidden inside the java.util package—you can’t directly reference them in your own code since they aren’t public. These are:

  • RegularEnumSet: Used when the enum has 64 or fewer elements. It stores the set using a single long value, making it super efficient for smaller enums.
  • JumboEnumSet: Used when the enum has more than 64 elements. It relies on an array of longs to handle the larger number of possible enum values.

The JDK automatically switches between these two based on the size of your enum, so you never have to manually pick one.

2. How do we get an instance of the abstract EnumSet type when EnumSet.of() returns EnumSet, and we haven't subclassed it?

This is a perfect example of the Factory Method Pattern in practice! EnumSet provides a suite of static factory methods (like of(), allOf(), noneOf(), etc.) that handle the creation of concrete instances on your behalf.

Here’s what happens under the hood when you call EnumSet.of(MyEnum.SOME_VALUE):

  1. The factory method first checks how many elements exist in your MyEnum type.
  2. It instantiates either RegularEnumSet or JumboEnumSet depending on that count.
  3. It returns the created instance as an EnumSet reference (the abstract type).

You don’t need to subclass EnumSet at all—just use these factory methods to grab instances, and program against the abstract EnumSet type. This hides implementation details from you, letting you focus on using the set instead of worrying about how it’s built.

For example:

enum Fruit { APPLE, BANANA, ORANGE }
EnumSet<Fruit> fruits = EnumSet.of(Fruit.APPLE, Fruit.BANANA);
// fruits is actually an instance of RegularEnumSet here, but you never need to interact with that class directly!

内容的提问来源于stack exchange,提问作者Foo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:29:07