Pergunta

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.

Foi útil?

Solução

It's giving you that warning because orderedBy is a static method and you're calling it on an instance of ImmutableSortedSet. 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 by copyOf(obj) (it's only being used to access the static method orderedBy, which could be used directly) and return an empty set, as if you had just called ImmutableSortedSet.orderedBy(myComparator).build().

Here's what you want to do (as R. Bemrose said):

ImmutableSortedSet<String> ordered = ImmutableSortedSet.copyOf(myComparator, obj);

For posterity, here's what I hastily posted initially (which has the same result):

ImmutableSortedSet<String> ordered = ImmutableSortedSet.orderedBy(myComparator)
    .addAll(obj).build();

Outras dicas

After looking at the Guava ImmutableSortedSet docs, it appears that you actually want one of the other overloads to copyOf.

Specifically, you want the copyOf(Comparator, Collection) overload:

Set<String> ordered = ImmutableSortedSet.copyOf(myComparator, obj);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top