简体   繁体   English

具有泛型的Java排序集合

[英]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(). 请注意,其他类型(非Bacon)也可以传递给asSortedList()。 How do I correctly modify this scenario so that the Bacon example works, and I can still pass in other types to asSortedList? 如何正确修改此方案,以使培根示例正常工作,并且仍然可以将其他类型传递给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>) Util类型的方法asSortedList(Collection <T>,Comparator <T>)不适用于参数(Collection <T>,Comparator <Bacon>)

Just change asSortedList to 只需将asSortedList更改为

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> . ...因为TBacon的子类型,而您的ComparatorComparator<Bacon>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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