Forums Register Login

PriorityQueue versus LinkedList

+Pie Number of slices to send: Send
Hello,

I'm preparing for an interview and I want to remember how to calculate the level in a binary tree.

I used PriorityQueue class.



For inputs I received the runtime exception :

6
3
5
4
7
2
1
3
Exception in thread "main" java.lang.ClassCastException: day23.Node cannot be cast to java.lang.Comparable
at java.util.PriorityQueue.siftUpComparable(PriorityQueue.java:633)
at java.util.PriorityQueue.siftUp(PriorityQueue.java:629)
at java.util.PriorityQueue.offer(PriorityQueue.java:329)
at day23.Day23.levelOrder(Day23.java:69)
at day23.Day23.main(Day23.java:86)
Java Result: 1

If I used LinkedList instead of PriorityQueue my code runs perfectly.

The reason I found him alone.

I need a comparator for Node class.





and when I created



So, PriorityQueue generated run time exceptions, while LinkedList not.






+Pie Number of slices to send: Send
Your Node doesn't implement Comparable.

PriorityQueue#insert javadoc wrote:Throws:
ClassCastException - if the specified element cannot be compared with elements currently in this priority queue according to the priority queue's ordering



The ordering in your case is the narutal ordering of elements (as you didn't provide any Comparator).

By the way, make your methods and variables non-static.
Joel Salatin has signs on his property that say "Trespassers will be Impressed!" Impressive tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 618 times.
Similar Threads
output the levelOrder traversal of a Binary search tree
Understanding how Successors and Predecessors work in code.
having trouble with recursion
Generic Binary Search Tree
Generics error.
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 18:53:14.