传递 ImmutableSet 代替 Set?
我有一个需要 Set 参数的方法。我想传入一个空集,并且我不希望该集有任何副作用。
我可以通过传入以下内容来对集合执行此操作:
Collections.unmodifiableSet(Sets.newHashSet())
但我想传入:
ImmutableSet.of()
如果我执行前者,则会创建 Set
...
Collections.unmodifiableSet(new HashSet<String>())
但看起来很丑,我想找到一种 Google Collections 方式。
I have a method that expects a Set parameter. I want to pass in an empty set, and I don't want any side effects on the Set.
I can do this with collections by passing in:
Collections.unmodifiableSet(Sets.newHashSet())
But I want to pass in:
ImmutableSet.of()
If I do the former a Set<Object>
is created and I get "method not applicable for args Set' error. If I do the latter I get ImmutableSet<Object>
is created and I get similar error.
This works:
Collections.unmodifiableSet(new HashSet<String>())
... but seems ugly, and I want to find a Google Collections way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试一下:
这也可以:
此语法对于在类型推断失败时手动指定类型参数非常有用。 :-)
Try this:
This will work too:
This syntax is useful for manually specifying type arguments any time the type inference fails. :-)
这也将起作用:
因为类型推断注意到您正在分配给
Set
变量,并且知道类型参数必须是String
。This will also work:
because the type inference notices that you are assigning to a
Set<String>
variable and knows that the type parameter must beString
.