简体   繁体   English

在Java中实现Comparable的堆

[英]Heap that implements Comparable in Java

I have an array that is full of Doubles and I want to save those doubles in a heap. 我有一个充满双打的数组,我想将那些双打保存在堆中。 The problem is I need to keep record of the index of the array. 问题是我需要记录数组索引。

Double[] array = new Double[n]; //imagine it's filled with doubles

Now I have a PriorityQueue: 现在我有了一个PriorityQueue:

PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); //Integer because it's an heap of indexes

I want to add each element of the array to the heap, but I want to keep record of the INDEX. 我想将数组的每个元素添加到堆中,但是我想保留INDEX的记录。 So imagine I add index 0 to the heap: 因此,假设我将索引0添加到堆中:

The heap stores 0, but uses array[0] to compare and sort it.
Not index 0 itself, that's just like a class index. Stores v but compares v.value

When I get a value from the heap: 当我从堆中获取值时:

Imagine I do heap.pull();
The heap returns me index 0, and then I will know the value is array[0].

Can I do this with comparable? 我可以用可比的方式做到这一点吗?

I hope I understand your question well. 希望我能很好地理解您的问题。 Try running the example below. 尝试运行以下示例。 See if you understand it and if this is the behaviour you are looking for. 看看您是否了解它,这是否是您要寻找的行为。

int n = 10;
final double[] arr = new double[n];
for (int i = 0; i < n; ++i) {
    arr[i] = Math.random() * 100;
}
PriorityQueue<Integer> queue = new PriorityQueue<>(n, new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return (int) (arr[o1] - arr[o2]);
    }
});

for (int i = 0; i < n; ++i) {
    queue.add(i);
}

System.out.println(Arrays.toString(arr));
System.out.println(queue.toString());

Note this can result in an OutOfBoundsException very quickly when you add something unexpected to the PriorityQueue . 请注意,当您向PriorityQueue添加意外内容时,这会很快导致OutOfBoundsException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM