0
因此,此代码的目的是使用排序阵列创建优先队列。通用对象获得空值而不是双值
目前我有一个C对象返回null,当我不相信它应该是。
相关代码:
int n = 5;
PQ<Double> pq1 = new PQasSortedArray<Double>(n);
double[] arr1 = new double[n];
for(int i = 0; i < n; i++){
Random num = new Random(); //Assigning random double values to the array
arr1[i] = num.nextDouble();
}
for (int i=0; i < arr1.length; i++){
pq1.insert(arr1[i]);
}
for (int i=arr1.length-1; i >=0 ; i--){
arr1[i] = pq1.deleteMin();
}
在我PQasSortedArray类,我有以下相关代码:
public class PQasSortedArray<C extends Comparable<? super C>> implements PQ<C> {
private C[] arr;
private int currentSize;
public PQasSortedArray(int size) {
arr = (C[]) new Comparable[size];
currentSize = 0;
}
public void insert(C data){
arr[currentSize++] = data;
}
public C min(){
C tmp = arr[0]; // <-- This gives tmp a value of null, which is not what I want
for(int i = 1; i < currentSize; i++) { // <-- This is skipped entirely as tmp is null
if(tmp.compareTo(arr[i]) > 0) {
tmp = arr[i];
}
}
return tmp;
}
public C deleteMin(){ // <-- This also doesn't work as intended
C tmp = arr[0];
arr[0] = arr[currentSize-1];
arr[currentSize-1] = null;
currentSize--;
return tmp;
}
所以我通常很不清楚如何去这个问题。我不习惯使用泛型,所以我可能会错过一些完全明显的东西。
public interface PQ<C extends Comparable<? super C>> {
public boolean isFull();
public boolean isEmpty();
public void insert(C data);
public C min();
public C deleteMin();
}
在第一块上市的代码是我一直在使用什么作为测试。给定5个double值,输出为5个double值,其索引由-1改变,所以0成为数组的最后一个,1成为0等。它应该删除数组的最小值,并返回一个数组大小为n-1,其中原始数组的大小为n。我已经知道我想要做的一部分是从插入方法中最不重要的数组中排序数据,但我仍然为什么tmp变为null而感到困惑。 – Nyxre
“这完全被跳过,因为tmp为空”如果tmp为空,则该行中没有任何内容会跳过。如果currentSize为零但是... – weston
请发布您的PQ界面。 – ceklock