I am just trying to insert some class objects in to a priority queue in java. But getting the error "com.java.split.MyComp cannot be cast to java.util.Collection". I tried different options by passing different parameter to,
PriorityQueue<Node> serverLog = new PriorityQueue<Node>();
Code:
import java.util.Comparator; import java.util.PriorityQueue;
public class Split {
public static void main(String args[])
{
Comparator comparator = new MyComp();
PriorityQueue<Node> serverLog = new PriorityQueue<Node>();
Node n1 = new Node(1,"one");
serverLog.add(n1);
Node n2 = new Node(1,"two");
serverLog.add(n2); <== Error Here (line 22)
Node n3= new Node(1, "three");
serverLog.add(n3);
}
}
public class Node {
private long timeStamp;
private String log;
public Node(long timeStamp, String log)
{
this.timeStamp = timeStamp;
this.log = log;
}
//getter and setter
}
public class MyComp implements Comparator {
@Override
public int compare(Object a, Object b) {
long aTimeStamp = ((Node) a).getTimeStamp();
long bTimeStamp = ((Node) b).getTimeStamp();
if(aTimeStamp == bTimeStamp)
return 0;
else if (aTimeStamp < bTimeStamp)
return 1;
else
return -1;
}
}
but none is working. I am getting the exception,
Exception in thread "main" java.lang.ClassCastException: com.java.split.Node cannot be cast to java.lang.Comparable at java.util.PriorityQueue.siftUpComparable(Unknown Source) at java.util.PriorityQueue.siftUp(Unknown Source) at java.util.PriorityQueue.offer(Unknown Source) at java.util.PriorityQueue.add(Unknown Source) at com.java.split.Split.main(Split.java:19)
There were lot of post suggesting to implement Comparator and override compare method but I could not fix it. I dont know the number of object that I am going to insert. kindly suggest what can be done to make this work?
Thank you!! -Bala