gpt4 book ai didi

JAVA GENERICS ERROR : have the same erasure, 但两者都没有覆盖另一个

转载 作者:行者123 更新时间:2023-12-01 22:17:45 24 4
gpt4 key购买 nike

为了好玩,我正在创建一个排序框架,以更好地理解各种排序算法。而且,我试图使其足够通用,以便它可以对实现扩展可比较接口(interface)的接口(interface)的任何内容进行排序。然而,java 编译器对我不满意。

这是我的界面:

public interface Sorter<C extends Comparable<C>>
{
void sort(C[] comparables);

void sort(C[] comparables, Comparator<C> comparator);
}

而且,这是我实现该接口(interface)的抽象类:

public abstract class AbstractSort<C extends Comparable<C>> implements Sorter
{
protected abstract void doSort(C[] comparables, Comparator<C> comparator);

final public void sort(C[] comparables)
{
sort(comparables, new Comparator<C>()
{
public int compare(C left, C right)
{
return left.compareTo(right);
}
});
}

final public void sort(C[] comparables, Comparator<C> comparator)
{
doSort(comparables, comparator);
}
}

而且,这是我遇到的错误:

java: name clash: sort(C[]) in AbstractSort and sort(java.lang.Comparable[]) in Sorter have the same erasure, yet neither overrides the other

Error:(25, 23) java: name clash: sort(C[],java.util.Comparator<C>) in AbstractSort and sort(java.lang.Comparable[],java.util.Comparator<java.lang.Comparable>) in Sorter have the same erasure, yet neither overrides the other

预先感谢您的帮助!

最佳答案

尝试写implements Sorter<C> 。如果没有类型参数,您将使用原始类型,这会禁用继承方法的泛型的某些方面。具体来说,使用原始父类(super class)型,您只能继承已删除的方法签名。在您的情况下,而不是继承方法 sort(C[] comparables)你继承了一个方法sort(Comparable[] comparables) ,您只能使用相同的签名来覆盖它。

通过指定Sorter<C>作为父类(super class)型,您继承了一个方法 `sort(C[] Compares),您可以使用相同的签名覆盖该方法。

像这样的陷阱就是为什么 Java 语言规范建议原始类型只能用于与非泛型遗留代码的接口(interface),并要求编译器在使用原始类型时发出警告。

关于JAVA GENERICS ERROR : have the same erasure, 但两者都没有覆盖另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30651379/

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