java - 对通用接口(interface)列表进行排序

标签 java generics sorting collections interface

是这样的,我有两个类A , B , 和一个通用接口(interface) C

Class A implements Comparable<A> {...}

interface C<T> {...}

//this class is not longer generic type, I do not know if this matter.
Class B extends A implements C<A> {...} 

然后,在其他类(class),我得到了一个 B如下列出并排序

List<B> list = new ArrayList<B>();
Collections.sort(list);

这非常有效,但现在我想更改 B 的列表到通用接口(interface) C , 使其更通用。

List<C<A>> list = new ArrayList<C<A>>();
Collections.sort(list);

这次报错如下:

Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<C<A>>). The inferred type C<A> is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

我试过如下修改(当然不行):

  1. 更改Cinterface C<T> extends Comparable<T>{...}
  2. 更改Bclass B extends A implements C<A>, Comparable<T> {...}

谁能帮帮我?

最佳答案

change C to interface C extends Comparable{...} Class B extends A implements C {...}

正如您已经从错误消息中看到的那样,这两者不能一起工作,因为 B 中会发生冲突。的定义 w.r.t 到 Comparable<A>Comparable<C<A>> .

A已经在实现 Comparable<A> ,你可以实现以下目标

List<C<A>> list = new ArrayList<C<A>>();
Collections.sort(list);

通过定义 Comparator对于 C<A>如下:

class CTComparator<T> implements Comparator<C<T>>
{
    @Override
    public int compare(C<T> o1, C<T> o2)
    {
        return 0;
    }
}

然后用这个比较器应用排序方法:

List<C<T>> list  = new ArrayList<C<T>>();
Collections.sort(list, comparator);

关于java - 对通用接口(interface)列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13338371/

相关文章:

java - 在 Java 中显式调用默认方法

java - java链接集实现

java - 如何从源文件夹中以 FileInputStream 形式读取图像?

Swift 通用序列可观察歧义

c++ - 可以根据任何属性对对象数组进行排序的函数模板

SQL 查询 - 在 UNION 中使用 Order By

java - 在 Java 中使用静态变量的优点

c# - 为什么包含命名参数会导致 "type arguments for method cannot be inferred from usage"错误?

c# - 使用配置文件中的字符串来初始化泛型

python - 按字典键的整数对字典进行排序