Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/309.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中是长数据类型或双数据类型_Java_Priority Queue_Comparable - Fatal编程技术网

优先队列中的排序重新获得第二项,该项在Java中是长数据类型或双数据类型

优先队列中的排序重新获得第二项,该项在Java中是长数据类型或双数据类型,java,priority-queue,comparable,Java,Priority Queue,Comparable,在Java中,如果我们想使用可比较的接口基于PriorityQueue中的第二项进行排序 代码如下所示: import java.util.*; public class Main{ public static class Pair implements Comparable{ int node; int weight; public Pair(int node,int weight){ this.node = n

在Java中,如果我们想使用可比较的接口基于PriorityQueue中的第二项进行排序 代码如下所示:

import java.util.*;
public class Main{

    public static class Pair implements Comparable{
        int node;
        int weight;
        public Pair(int node,int weight){
            this.node = node;
            this.weight = weight;
        }

        @Override
        public int compareTo(Object o) {
            return this.weight - ((Pair)o).weight;
        }
    }


    public static void main(String [] args){
        PriorityQueue<Pair> pq = new PriorityQueue<Pair>();
        pq.add(new Pair(2,3));
        pq.add(new Pair(2,3));
    }
}
import java.util.*;
公共班机{
公共静态类对实现了可比较的{
int节点;
整数权重;
公共对(整数节点,整数权重){
this.node=节点;
重量=重量;
}
@凌驾
公共整数比较对象(对象o){
返回此.weight-((对)o).weight;
}
}
公共静态void main(字符串[]args){
PriorityQueue pq=新的PriorityQueue();
pq.添加(新的一对(2,3));
pq.添加(新的一对(2,3));
}
}
但是,如果权重数据类型将是长的或双倍的,那么对于这种情况,如何处理排序优先级队列

需要帮助!提前感谢。

公共静态类对{
public static class Pair implements Comparable<Pair>{
    int node;
    Double weight;
    public Pair(int node,double weight){
        this.node = node;
        this.weight = weight;
    }


    @Override
    public int compareTo(Pair o) {
        return this.weight.compareTo(o.weight);
    }
}
int节点; 双倍重量; 公共对(int节点,双权重){ this.node=节点; 重量=重量; } @凌驾 公共整数比较(o对){ 返回此.weight.compareTo(o.weight); } }
您是说,重量可以是整数、长码或双精度?您可以使用double type作为权重。这将不起作用,因为Compariable接口没有任何CompatieTo方法,返回类型为long或double。为什么期望将long或double作为ComparieTo方法的返回类型。在这里读一次好的,但是如果权重数据类型是long或double,我应该在compareTo方法下写什么:(我的比较逻辑基于第二个[long/double]类型的项目排序,将是this.weight-((Pair)o)。权重现在工作很长,或者double只对int起作用