Wes
Wes

Reputation: 1257

Writing a generic method for sorting a set of comparables of any type

I have something like this:

public class A implements Comparable<A> {
  ...
  @Override
  public int compareTo(A obj) {
     ...
  }
}

public class B implements Comparable<B> {
  ...
  @Override
  public int compareTo(B obj) {
     ...
  }
}

I also have a bunch of HashSet collections that are slowly populated over the course of a program, e.g.:

private Collection<A> col = new HashSet<A>();

At the very end of the program I would like to convert them to sorted lists so they can be displayed sorted:

public class Utils {
  public static <T> Collection<Comparable<T>> toSortedList(Collection<Comparable<T>> col) {
    List<Comparable<T>> sorted = new ArrayList<Comparable<T>>(col);
    Collections.sort(sorted);
    return sorted;
  }
}

Unfortunately I get the compile error:

The method sort(List<T>) in the type Collections is not applicable for the arguments (List<Comparable<T>>)

How do I go about modifying the above so HashSets of both Comparable<A> and Comparable<B> can be passed to this method? Thanks!

Upvotes: 0

Views: 79

Answers (1)

Nikolay Lebedev
Nikolay Lebedev

Reputation: 344

Use <T extends Comparable<? super T>> generic syntax:

public class Utils {
    public static <T extends Comparable<? super T>> Collection<T> toSortedList(Collection<T> col) {
        List<T> sorted = new ArrayList<T>(col);
        Collections.sort(sorted);
        return sorted;
    }
}

Upvotes: 3

Related Questions