Alexander Dragnev :
I have implemented it with the Priority queue because of the task. My question is why it is working like this:
public <T> void heapSort(List<T> elements){
PriorityQueue<T> q = new PriorityQueue<>(elements);
elements.clear();
while (!q.isEmpty()){
elements.add(q.poll());
}
}
But it stops working when I change it with a wildcard?
public void heapSort(List<?> elements){
PriorityQueue<?> q = new PriorityQueue<>(elements);
elements.clear();
while (!q.isEmpty()){
elements.add(q.poll());
}
}
Andy Turner :
Please, someone, explain to me why?
In general, you can't add elements from a PriorityQueue<?>
into a List<?>
, because the queue might be a PriorityQueue<String>
and the list might be a List<Integer>
.
The compiler doesn't "remember" that the type parameter is the same in both cases, unless you create a type variable to tell it they are the same.
and how to fix it.
You know how to fix it: use a type variable, as in the first code example.
If you mean how not to have the type variable in the method signature, you can delegate to a private method:
public void heapSort(List<?> elements) {
heapSortPrivate(elements);
}
private <T> void heapSortPrivate(List<T> elements){
PriorityQueue<T> q = new PriorityQueue<>(elements);
elements.clear();
while (!q.isEmpty()){
elements.add(q.poll());
}
}