0

I get a random collection and would like to sort it using generics. As an example, see the code below:

abstract class Foo<T extends Bacon>{
  public Foo(Collection<T> bacons){
    List sorted = Util.asSortedList(bacons, Util.BACON_COMPARATOR);
  }
}

class Util{
  public static final Comparator<Bacon> BACON_COMPARATOR = new Comparator<Bacon>() {
      @Override
      public int compare(final Bacon one, final Bacon two) {
          return one.getId().compareTo(two.getId());
      }
  };

  public static <T> List<T> asSortedList(Collection<T> c, Comparator<T> comparator) {
      List<T> list = new ArrayList<T>(c);
      Collections.sort(list,comparator);
      return list;
  }
}

Please note that other types (non-Bacon) may be passed into asSortedList(). How do I correctly modify this scenario so that the Bacon example works, and I can still pass in other types to asSortedList?

The code shown above gives me the following error:

The method asSortedList(Collection<T>, Comparator<T>) in the type Util is not applicable for the arguments (Collection<T>, Comparator<Bacon>)

1
  • 2
    That looks good. What does not work? Do you get any compile errors for that? Commented Dec 18, 2014 at 1:30

1 Answer 1

5

Just change asSortedList to

public static <T> List<T> asSortedList(
    Collection<T> c, Comparator<? super T> comparator)

...since T is a subtype of Bacon, and your Comparator is a Comparator<Bacon>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.