【发布时间】:2013-05-11 19:17:42
【问题描述】:
我有一个界面
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而不是HashSet是否真的对效率至关重要,或者仅仅是为了使用EnumSet?从泛型角度来看,您最终似乎是在尝试创建一些堆污染,因为您已经创建了Terms 的Set,但正在尝试将Common的实例添加到其中。 -
是的,现在我意识到如果我想做 add() 我需要在终端符号的枚举中添加 EPSILON 符号,但我需要在公共枚举中使用这个 epsilon 符号所以我必须使用
HashSet解决方案:D