从 EnumSet 转换设置当A继承B时
标题基本上已经解释了这个问题。我有一个接口方法:
Set<Field> getFieldSet()
并且我有一个类 User
,它看起来像这样
class User {
enum Fields implements Field {
USERNAME, PASSWORD;
...
}
...
}
现在我想实现 User
的 getFieldSet()
方法。天真的方法似乎只是 return EnumSet.allOf(Fields.class)
但我收到以下错误:
> Type mismatch: cannot convert from Set<User.Fields> to Set<Field>
除了手动将 EnumSet 复制到 Set
之外,还有其他方法吗?有好的方法吗?
The title pretty much explains the question. I have an interface method:
Set<Field> getFieldSet()
and I have a class, User
which looks something like this
class User {
enum Fields implements Field {
USERNAME, PASSWORD;
...
}
...
}
Now I want to implement User
's getFieldSet()
method. The naive way seems to just return EnumSet.allOf(Fields.class)
but I get the following error:
> Type mismatch: cannot convert from Set<User.Fields> to Set<Field>
Other than manually copying the EnumSet to Set<Field>
, is there a good way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以返回
new HashSet(EnumSet.allOf(Fields.class));
。这将绕过这样一个事实:您无法将
Set
类型的值分配给Set
类型的变量。或者,您的界面可以是
Set getFields() 代替。您可以将
Set
分配给捕获变量。You could return
new HashSet<Field>(EnumSet.allOf(Fields.class));
.That will get around the fact that you can't assign a value of type
Set<User.Fields>
to a variable of typeSet<Field>
.Alternatively, your interface could be
Set<? extends Field> getFields()
instead. You can assignSet<User.Field>
to a capturing variable.使用 集合。 unmodifierSet:
优点:
Set
,而不是一个设置
缺点:
Use Collections.unmodifiableSet:
Pros:
Set<Field>
, not aSet<? extends Field>
Cons:
这不起作用的原因是
Set
不是Set
的子类型。例如,如果您从方法返回Set
,您可能会遇到如下情况:这里最好的选择是使用不同的 set 实现(通常是不可修改的 set)来返回价值观。例如:
或者,如果您需要该集合是可变的(通常可能不是一个好主意)
The reason this doesn't work is that
Set<Fields>
isn't a subtype ofSet<Field>
. For example, if you returned aSet<Fields>
from your method, you could get a situation like the following:Your best option here is to use a different set implementation (usually an unmodifiable set) to return the values. For example:
or, if you need the set to be mutable (probably not a good idea, usually)
这是我认为一个很好的解决方案。这不完全是你想要的,但足够接近
Here is I think a good solution. It's not exactly what you want but close enough