Reputation: 309
I am lost in code. I am trying to add a returned value into an ArrayList. The returned value is printed and I have tried to cast it so I can add it to an ArrayList. But nothing seems to be working.
I am in public void getHeap()
and like to retrieve the return
value from public double remove()
to add in an ArrayList. It keeps on telling me source not found
. Any help?
Thanks!
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) {
//....
}
}
Upvotes: 0
Views: 706
Reputation: 6718
You're calling remove()
twice:
while (!heap.isEmpty()) {
System.out.println(heap.remove());
newArray.add(heap.remove());
}
On the final iteration, when there's only one item left, the second call will fail.
I think your intention is:
while (!heap.isEmpty()) {
final Double removed = heap.remove();
System.out.println(removed);
newArray.add(removed);
}
Upvotes: 0
Reputation: 86774
Try using this instead:
public E remove() {
E removedNode = h.get(0);
E lastNode = h.remove(h.size() - 1);
percolateDown(0, lastNode);
return removedNode;
}
Also, I think arrayPostingList
should be of type E
, not explicitly Double
.
Upvotes: 1