构造 ImmutableSortedSet 而不发出警告
我想要构造ImmutableSortedSet
。我编写了如下代码 smt:
Set<String> obj = new HashSet<String>();
Comparator<String> myComparator = new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return 0;
}
};
Set<String> ordered = ImmutableSortedSet.copyOf(obj)
.orderedBy(myComparator).build();
但它会生成警告:
静态方法 orderBy(比较器) 来自 ImmutableSortedSet 类型应该 以静态方式访问
如何在没有 @SuppressWarnings("static-access")
的情况下删除此警告?谢谢。
I want construct ImmutableSortedSet
. I wrote code smt like:
Set<String> obj = new HashSet<String>();
Comparator<String> myComparator = new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return 0;
}
};
Set<String> ordered = ImmutableSortedSet.copyOf(obj)
.orderedBy(myComparator).build();
but it generates warning:
The static method
orderedBy(Comparator) from the
type ImmutableSortedSet should
be accessed in a static way
How can I remove this warning without @SuppressWarnings("static-access")
? Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
它向您发出该警告是因为
orderedBy
是静态方法,并且您在ImmutableSortedSet
的实例上调用它。这通常意味着你认为自己在做一件事,而实际上你在做另一件事,这里就是这种情况。结果是这段代码不会做你认为它会做的事情......它将丢弃由
copyOf(obj)
创建的ImmutableSortedSet
(它只是用于访问静态方法orderedBy
,可以直接使用)并返回一个空集,就像您刚刚调用ImmutableSortedSet.orderedBy(myComparator).build()
。这就是你想要做的(正如 R. Bemrose 所说):
为了后代,这是我最初匆忙发布的内容(具有相同的结果):
It's giving you that warning because
orderedBy
is a static method and you're calling it on an instance ofImmutableSortedSet
. This often means you think you're doing one thing when really you're doing something else, and that's the case here.The result is that this code isn't going to do what you think it does... it's going to throw away the
ImmutableSortedSet
created bycopyOf(obj)
(it's only being used to access the static methodorderedBy
, which could be used directly) and return an empty set, as if you had just calledImmutableSortedSet.orderedBy(myComparator).build()
.Here's what you want to do (as R. Bemrose said):
For posterity, here's what I hastily posted initially (which has the same result):
查看 Guava
ImmutableSortedSet
文档后,您似乎实际上想要copyOf
的其他重载之一。具体来说,您需要
copyOf(Comparator, Collection)
重载:After looking at the Guava
ImmutableSortedSet
docs, it appears that you actually want one of the other overloads tocopyOf
.Specifically, you want the
copyOf(Comparator, Collection)
overload: