Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/codeigniter/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java中实现Comparable的堆_Java - Fatal编程技术网

在Java中实现Comparable的堆

在Java中实现Comparable的堆,java,Java,我有一个满是双精度的数组,我想把这些双精度保存在一堆中。 问题是我需要记录数组的索引 Double[] array = new Double[n]; //imagine it's filled with doubles 现在我有一个优先队列: PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); //Integer because it's an heap of indexes 当我从堆中获取值时: T

我有一个满是双精度的数组,我想把这些双精度保存在一堆中。 问题是我需要记录数组的索引

Double[] array = new Double[n]; //imagine it's filled with doubles
现在我有一个优先队列:

PriorityQueue<Integer> heap = new PriorityQueue<Integer>(); //Integer because it's an heap of indexes
当我从堆中获取值时:

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
Imagine I do heap.pull();
The heap returns me index 0, and then I will know the value is array[0].

我能用comparable做这个吗?

我希望我能很好地理解你的问题。尝试运行下面的示例。看看你是否理解它,这是否是你正在寻找的行为

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());
int n=10;
最终双精度[]arr=新双精度[n];
对于(int i=0;i

注意:当您向
PriorityQueue

添加一些意想不到的内容时,这可能会很快导致
outofbounds异常。该术语通常指用于内存分配和垃圾回收的空间,而不是优先级队列。我还认为这是一个XY问题——你在问我们,一个特定的半编码解决方案是否可以工作,而不告诉我们你想解决什么问题。。。答案可能是,这是解决问题的错误方法,但我们不能用你给我们的答案来回答。就目前而言,我必须投票支持“close As unclude”。此外,Compariable是在您想要比较的对象上实现的,而不是在容器上实现的,因此它可能不是您想要的。答案可能是创建一个新类,而不是直接使用double和integer。这个问题解释正确,heap确实在priorityqueue中有一个应用程序,我写的是一个我想做的算法,所以我可以在Java中找到一个解决方案。现在我将独自找到它,然后写在这里,这样你们就可以看到我的问题并不清楚!!堆实际上是一种数据结构。