Java 优先级队列删除功能不工作

Java 优先级队列删除功能不工作,java,Java,对于此类,优先级队列的remove函数工作不正常 当实现dijkstra的算法时。这是我创建的类 对优先级队列中的元素进行排序。尽管优先级队列正在删除 min元素正确,其removeobject o方法不正确 正确移除元件 public class IntegerArray implements Comparable<IntegerArray> { public double[] a; IntegerArray(double x,double y){ a= new do

对于此类,优先级队列的remove函数工作不正常 当实现dijkstra的算法时。这是我创建的类 对优先级队列中的元素进行排序。尽管优先级队列正在删除 min元素正确,其removeobject o方法不正确 正确移除元件

public class IntegerArray implements Comparable<IntegerArray> {

public double[] a;

IntegerArray(double x,double y){

    a= new double[2];
    a[0]=x;
    a[1]=y;

}

public boolean equals(IntegerArray x){
    if(this.a[0]==x.a[0] & this.a[1] ==x.a[1]){
        return true;
    }
    else return false;
}

public int compareTo(IntegerArray x){
    if(this.a[1] > x.a[1]){
        return 1;
    }
    else if(this.a[1] < x.a[1]){
        return -1;
    }
    else return 0;
}
///////这是使用优先级队列的Dijsktra算法的代码

for (int i = 0; i < graph.get((int) node).size(); i++) {
  alt = (int) (dist[(int) node] + graph.get((int)      node).get(i).weight);
   if (alt < dist[ graph.get((int) node).get(i).vertex]) {
     temp1.a[0]=graph.get(node).get(i).vertex;
     temp1.a[1]=dist[graph.get(node).get(i).vertex];
     System.out.println("temp1" +" "+ temp1.a[0]+ " "+ temp1.a[1]);
     Q.remove(temp1);   //it is not removing though the object   instance is present in the queue
    dist[graph.get(node).get(i).vertex] = alt;
   pred[graph.get(node).get(i).vertex] = node;
   temp1.a[1]=dist[graph.get(node).get(i).vertex]; 
   System.out.println("temp1" +" "+ temp1.a[0]+ " "+ temp1.a[1]);
   Q.add(temp1);

}
你的方法不正确。正确的方法具有签名public boolean equalsObject o,而您的方法具有public boolean equalsIntegerArray x。参数类型不同,方法不同

在PriorityQueue.remove中,调用的是equalsObject,因为您没有定义它,所以默认实现称为身份比较

请尝试以下方法:

public boolean equals(Object o){
    IntegerArray x = (IntegerArray)o;
    return this.a[0] == x.a[0] && this.a[1] == x.a[1];
}

[更新]减少了代码冗余。

我的错误是我传递的是重复对象的引用,即temp1,而不是原始对象的引用

您还需要重写int hashCode函数。您可以粘贴运行程序时在控制台上看到的输出以及队列中有哪些元素吗@parakmiakos我不认为hashcode在这里会有帮助,即priorityqueue不使用他正在创建一个新的对象temp1,然后调用removetemp1。我认为他需要重写hashCode,因为他基本上是要求从队列中删除一个与另一个具有相同值的对象,而不是相同引用。它打印队列中存在的元素,但在调用Q.removetemp1时返回false,尽管remove函数返回true,它并不总是删除指定的元素,而是删除第一个元素。如果返回true,则表示它删除了某些内容。同一元素添加了两次吗?是否可以打印所有值以查看具体更改的内容?这是在删除队列中的min元素。将IntegerArray实例添加到PriorityQueue时,还应创建新的IntegerArray实例。在代码中,重用temp1,它似乎是您添加的唯一实例。True。那是你犯错误的根本原因。但是,看看其他答案,了解为什么会发生这种情况,以及正确的方法是什么。