gpt4 book ai didi

java - 为什么这个 Java 泛型代码不能正常工作?

转载 作者:行者123 更新时间:2023-12-02 05:56:32 26 4
gpt4 key购买 nike

我有以下代码:

public abstract class Heap {

Comparable<?> data[];

int count, size;

public Heap( int size ) {

this.size = size;

data = new Comparable<?>[ size + 1 ];

this.count = 0;
}

public abstract void insert( Comparable<?> item );

}

class MinHeap extends Heap {

public MinHeap (int size ) { super(size); }

public void insert( Comparable<?> item ) {

//this line here is giving me an error
//due to how I am storing the array in Heap

int k = data[ 0 ].compareTo( item );

}
}

上面指出的行给了我这个错误:The method compareTo(capture#1-of ?) in the type Comparable<capture#1-of ?> is not applicable for the arguments (Comparable<capture#2-of ?>) 。我无法找到一种方法让它在保持这些条件的同时工作:1)我希望 MinHeap 能够处理任何实现 Comparable 的数据。 ,2)我不想将预初始化的数组传递到构造函数中。我这样说是因为我不想执行以下操作:

abstract class Heap< T extends Comparable<T> > {

T data[];

public Heap( T data[], int size ) {

this.data = data;
//I do not want to have to pass an instantiated array.
//I want the constructor to handle the instantiation. If I do this I know the issue with the
//compareTo will be solved, but I really prefer to avoid this.
}

}

我的问题是:在我的代码中,为什么会出现此错误?除了第二个示例中描述的方法之外,还有人知道另一种方法吗?我希望能够使用任何可比较的数据创建一个最小堆数据结构。感谢所有有帮助的评论。谢谢。

旁注:不必担心实例变量的访问修饰符。为了简单起见,我将它们保留为默认值。我确实知道它们应该对 setter/getter 是私有(private)的或 protected 。

最佳答案

首先,这段代码对于创建通用数组是无效的:

data = new Comparable<?>[ size + 1 ];

This link in the Java Trails解释了为什么它是非法的,但归根结底是数组必须在编译时知道它们的类型,而泛型基于类型删除工作并且可以在运行时推断。

但在我们解决这个问题之前,您的泛型存在一个问题 - 它们并不是真正的...泛型。您在这里仅使用通配符泛型,没有任何限制。

如果你想让你的抽象类有一个充满Comparable的通用数组,那么你想让你的抽象类绑定(bind)到 Comparable<T> ,并将您的数据简单地绑定(bind)到 T 。有了这个,我们最终可以将数组初始化修复为可编译(但未经检查的强制转换)形式:

data = (T[]) new Comparable[size + 1];

这是完整的类(class)供引用。它接近您的第二种形式,并且不需要您传入实例化数组。此外,由于T绑定(bind)到Comparable<T> ,我们不需要将其声明为方法中的参数 - 我们可以简单地提供 T .

public abstract class Heap<T extends Comparable<T>> {
T data[];
int count, size;

public Heap(int size) {
this.size = size;
data = (T[]) new Comparable[size+1];
this.count = 0;
}

public abstract void insert(T item);

}

对于此示例,您还希望将泛型类型添加到您的子类中:

class MinHeap<T extends Comparable<T>> extends Heap<T>    

关于java - 为什么这个 Java 泛型代码不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23045602/

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