• Post Reply Bookmark Topic Watch Topic
  • New Topic

PriorityQueue versus LinkedList  RSS feed

 
Dana Ucaed
Ranch Hand
Posts: 406
6
Netbeans IDE Oracle Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.






 
Paweł Baczyński
Bartender
Posts: 2087
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!