gpt4 book ai didi

java - 使用实现接口(interface)的枚举的 EnumSet

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:28:38 27 4
gpt4 key购买 nike

我有一个界面

public interface TerminalSymbol {
// methods ...
}

枚举

// common usage enum that I need
public enum Common implements TerminalSymbol {
EPSILON;

@Override
// methods ...
}

我想做这样的事情:

enum Term implements TerminalSymbol {
A, B, C, ...

@Override
// methods ...
}

EnumSet<? extends TerminalSymbol> terminalSymbols = EnumSet.allOf(Term.class);
terminalSymbol.add(Common.EPSILON); // this line gives me error

那个错误是(在我的例子中):

The method add(capture#1-of ? extends TerminalSymbol) in the type AbstractCollection<capture#1-of ? extends TerminalSymbol> is not applicable for the arguments (Common)

现在我知道如果我使用 Set<SomeInterface>我可以防止这种类型的错误(并且我可以继续开发代表正式语法的类)但我想使用 EnumSet因为它可能比 HashSet 更有效率.我该如何解决这个问题?

最佳答案

EnumSet 只能包含一个枚举类的成员。

来自Java API documentation :

All of the elements in an enum set must come from a single enum type that is specified, explicitly or implicitly, when the set is created.

如您所见,另一种方法是使用 Set<TerminalSymbol> .

关于java - 使用实现接口(interface)的枚举的 EnumSet,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16595187/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com