gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:20:17 24 4
gpt4 key购买 nike

是这样的,我有两个类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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com