简体   繁体   中英

Java sorting collections with generics

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

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM