通用对象获取空值而不是double值

时间:2017-02-18 23:05:58

标签: java arrays generics priority-queue

因此,此代码的目的是使用排序数组创建优先级队列。

目前我有一个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(); 

}

1 个答案:

答案 0 :(得分:0)

在测试结束时currentSize == 1:

public C deleteFirst() { // <-- This also doesn't work as intended
    C tmp = arr[0];
    arr[0] = arr[currentSize - 1];
    arr[currentSize - 1] = null;
    currentSize--;
    return tmp;
}

变为:

public C deleteFirst() { // <-- This also doesn't work as intended
    C tmp = arr[0];
    arr[0] = arr[0];
    arr[0] = null;
    currentSize--;
    return tmp;
}

最终:arr [0] == null和currentSize == 0.

tmp = arr [0] == null:

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 min() {
    if (currentSize == 0) {
        throw new RuntimeException("Size is 0.");
    }

    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;

}