From the API of poll-method of PriorityQueue-class:
Retrieves and removes the head of this queue, or returns null if this queue is empty.
Harold Ndou wrote:Why system.out.println(pq1.poll() + " ") produce 1 3 5 6 7 8 9, i understand that method poll() retrieve head element and remove it from the queue, i dnt understand why it did not remove head.
So your understanding is correct: when using poll the head of the queue will be retrieved and removed. Why do you think the head was not removed? Because with the current code you can't know if the head was removed or not. Try adding
System.out.println("size " + pq1.size()); after line 16 (in the above code snippet). And before running the updated code snippet,
you should first try to think yourself about the expected output of this new line.
Harold Ndou wrote:And other thing is that system.out.print(pq2.pol() + " ") produce 8 7 6 5 3 1 null, i dont understand the null at the end.
Have another close look at the 1st line of this post and you'll definitely know why
null was printed.