Implementing Java Comparator

前端 未结 2 396
栀梦
栀梦 2020-12-09 17:32

I am trying to write an algorithm which utilizes a min-priority queue, so I looked around on google and found the PriorityQueue. It seems that in order to use it, though, I

相关标签:
2条回答
  • 2020-12-09 18:16

    As you can see here (the JSE Comparator JavaDoc page), the Comparator interface has a generic "parameter" describing the type for which this comparator is designed. The PriorityQueue is similar.

    So, if you create a PriorityQueue<Node1>, you can create a Comparator<Node1> as follows:

    public class distComparator implements Comparator<Node1> {    
        @Override
        public int compare(Node1 x, Node1 y){
            return x.dist - y.dist;
        }
    }
    
    0 讨论(0)
  • 2020-12-09 18:21

    You need to implement Comparator<Node1>:

    public class distComparator implements Comparator<Node1> {
                                                     ^^^^^^^
    

    Without this, you are implementing Comparator<Object>, which isn't what you want (it can be made to work, but isn't worth the hassle).

    The rest of the code in your question is fine, provided Node1 has an accessible member called dist.

    Note that if you are using Java 7, the entire body of the method can be replaced with

    return Integer.compare(x.dist, y.dist);
    

    (replace Integer with Double etc, depending on the type of Node1.dist.)

    0 讨论(0)
提交回复
热议问题