Reputation:
This is a homework problem:
I have a generic class defined as follows:
public class PriorityQueue<T extends Comparable<T>> {
ArrayList<T> queue;
public PriorityQueue(){
queue = new ArrayList<>();
}
void add(T t){
queue.add(t);
Collections.sort(queue);
}
<T extends Comparable<T>> T remove(){
T t = queue.get(0);
queue.remove(t);
return t;
}
}
but NetBeans is showing the following error (red-underline) on the line T t = queue.get(0)
:
incompatible types
required: T#2
found: T#1
where T#1,T#2 are type-variables:
T#1 extends Comparable<T#1> declared in class PriorityQueue
T#2 extends Comparable<T#2> declared in method <T#2>remove()
It seems as though somehow it's not understanding that the T
type I'm referring to in the method declaration is the same as the one referred to in the type parameter of the class. I'm guessing this is some sort of a syntax issue.
I also wonder if I'm overcomplicating things - it would seem more logical to me if I simply declared the method with T remove() {
. This compiles correctly, but when I try to test it using a driver class as follows:
PriorityQueue pq = new PriorityQueue<Integer>();
int a = 10;
int b = 12;
int c = 5;
int d = 9;
pq.add(a);
pq.add(b);
pq.add(c);
pq.add(d);
Integer i = pq.remove();
I get the error:
Incompatible types:
required: Integer
found: Comparable
on the line Integer i = pq.remove();
As is probably obvious, I'm just learning how to use generics. Please help me understand where I'm going wrong here.
Upvotes: 0
Views: 55
Reputation: 136162
change
PriorityQueue pq = new PriorityQueue<Integer>();
to
PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
remove method should be
T remove() {
...
Upvotes: 3