Search code examples
javaexceptionpriority-queuecomparable

Java - how to push a pair of 3 integers into Priority-Queue?


I'm trying to add 3-integer pair into priority-queue. First pair shows no problem, but when I'm pushing the next pair, I'm getting an exception. Here's my code and the exception:

import java.util.*;
class pair2{
    public int first, second;
    public pair2(int a, int b){
        this.first = a;
        this.second = b;
    }
}

class pair3{
    public  int first3;
    public  pair2 second3;
    public pair3(int a, int b, int c){
        this.first3 = a;
        this.second3 = new pair2(b, c);
    }
}

public class WATER{
  public static void main(String args[]){
    PriorityQueue<pair3> p = new PriorityQueue<pair3>();
    pair3 temp = new pair3(1, 2, 3);
    p.add(temp);
    temp = new pair3(2, 1, 4);
    p.add(temp);
    while (!p.isEmpty()){
        temp = p.poll();
        System.out.println(temp.first3);
    }
  }
}

And the exception is:

Exception in thread "main" java.lang.ClassCastException: pair3 cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:652)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:647)
at java.util.PriorityQueue.offer(PriorityQueue.java:344)
at java.util.PriorityQueue.add(PriorityQueue.java:321)
at WATER.main(WATER.java:25)

I think there's some problem of comparison while inserting the next pair, I don't know what to do. Any help will be appreciated. Thanks in advance.


Solution

  • PriorityQueue is a binary heap, so items will be ordered in the heap upon insertion/removal and you aren't telling it how to compare elements. You can make pair implements Comparable or pass a Comparator

    class pair3 implements Comparable<pair3>{
     //
    }
    

    Or provide a comparator

    PriorityQueue<pair3> p = new PriorityQueue<pair3>(new Comparator<>{
     ..
    });