Frage

Ich möchte Konstrukt ImmutableSortedSet. Ich schrieb Code smt wie:

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();

, aber es erzeugt Warnung:

Die statische Methode orderedBy (Komparator) aus dem Typ ImmutableSortedSet sollte in einer statischen Art und Weise zugegriffen werden

Wie kann ich diese Warnung ohne @SuppressWarnings("static-access") entfernen? Danke.

War es hilfreich?

Lösung

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();

Andere Tipps

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);
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top