我迷失了代码。我试图将返回的值添加到ArrayList中。返回的值已打印,并且我尝试过强制转换,因此可以将其添加到ArrayList中。但是似乎没有任何作用。

我在public void getHeap()中,喜欢从return检索public double remove()值以添加到ArrayList中。它一直告诉我source not found。有什么帮助吗?

谢谢!

public class MinHeap<E extends Comparable<E>> {

    List<E> h = new ArrayList<E>();
    ArrayList<Double> arrayPostingsList = new ArrayList<Double>();

    public void getHeap() {
        MinHeap<Double> heap = new MinHeap<Double>(new Double[]{0.5015530788463572, 0.5962770626486013, 0.4182157748994399});

        ArrayList<Double> newArray = new ArrayList<Double>();
        System.out.println();


        while (!heap.isEmpty()) {
            System.out.println(heap.remove());
            newArray.add(heap.remove());
        }

    }

    public double remove() {
        E removedNode = h.get(0);
        E lastNode = h.remove(h.size() - 1);
        percolateDown(0, lastNode);

        return (Double) removedNode;
    }

    public MinHeap() {
    }

    public MinHeap(E[] keys) {
        for (E key : keys) {
            h.add(key);
        }

        for (int k = h.size() / 2 - 1; k >= 0; k--) {
            percolateDown(k, h.get(k));
        }
    }

    public void add(E node) {
        h.add(null);
        int k = h.size() - 1;
        while (k > 0) {
            int parent = (k - 1) / 2;
            E p = h.get(parent);
            if (node.compareTo(p) >= 0) {
                break;
            }
            h.set(k, p);
            k = parent;
        }
        h.set(k, node);
    }

    public E min() {
        return h.get(0);
    }

    public boolean isEmpty() {
        return h.isEmpty();
    }

    void percolateDown(int k, E node) {
        //....
    }
}

最佳答案

您要拨打remove()两次:

while (!heap.isEmpty()) {
    System.out.println(heap.remove());
    newArray.add(heap.remove());
}


在最后一次迭代中,当仅剩一个项目时,第二个调用将失败。

我认为您的意图是:

while (!heap.isEmpty()) {
    final Double removed = heap.remove();
    System.out.println(removed);
    newArray.add(removed);
}

08-06 11:14