Reputation: 75
I am trying to create a Priority Queue with Nodes of doubly Linked List to sort the doubly linked list . https://www.codingninjas.com/codestudio/problems/sort-a-k-sorted-doubly-linked-list_1118118?leftPanelTab=0
/****************************************************************
Following is the class structure of the Node class:
class Node<T> {
T data;
Node<T> next;
Node<T> prev;
public Node(T data) {
this.data = data;
}
}
*****************************************************************/
import java.util.*;
public class Solution {
static class compareNode implements Comparator<Node>
{
public int compare(Node n1, Node n2){
return n1.data-n2.data;
}
}
public static Node<Integer> sortedDll(Node<Integer> head, int k) {
PriorityQueue<Node> pq = new PriorityQueue<Node>(new compareNode());
/* logic goes here*/
return head;
}
}
i am getting below error when i run the above program
Compilation Failed
./Solution.java:21: error: bad operand types for binary operator '-'
return n1.data-n2.data;
^
first type: Object
second type: Object
1 error
can anyone tell why i am getting this error? and how to rectify it?
Upvotes: 1
Views: 54
Reputation: 719159
You cannot subtract an arbitrary object from another one
What you are actually trying to do here is to subtract one T
from another T
. That is not a valid thing to do in general. (The erasure of T
is Object
.)
That means that
static class compareNode implements Comparator<Node> {
public int compare(Node n1, Node n2){
return n1.data-n2.data;
}
}
is not going to work.
But ... wait ... the problem actually requires your code to compare Node<Integer>
instances rather than Node<?>
instances. So what you need is something a bit like this:
static class compareNode implements Comparator<Node<Integer>> {
public int compare(Node<Integer> n1, Node<Integer> n2){
return n1.data-n2.data;
}
}
... and I think you will find that that compiles. But it is not correct. The correct way to write that is:
static class compareNode implements Comparator<Node<Integer>> {
public int compare(Node<Integer> n1, Node<Integer> n2){
return n1.data.compareTo(n2.data);
}
}
The problem is that when you subtract one integer from another you can get integer overflow ... and a result with the wrong sign.
Another way to solve this is attempt cast the data
values of a Node<T>
to Comparable<?>
and then use Comparable.compare
. This approach would involve some implicit and explicit runtime type checks ... and could in theory produce ClassCastException
s.
Upvotes: 1