Results 1 to 2 of 2
- 10-06-2011, 01:45 PM #1
Member
- Join Date
- Aug 2011
- Posts
- 20
- Rep Power
- 0
difference of add method between Queue class and Stack class
error information:Java Code:import java.util.*; public class PriorityQueueTest { Queue<Number> queue = new PriorityQueue<Number>(); Number a; public PriorityQueueTest(){ queue.offer(1000); queue.offer(33.23); queue.offer(100.2); queue.offer(92); queue.offer(-21); while ( (a = queue.poll()) !=null ) { System.out.println(a); } } public static void main(String[] args) { new PriorityQueueTest(); } }
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
at java.lang.Double.compareTo(Unknown Source)
at java.util.PriorityQueue.siftUpComparable(Unknown Source)
at java.util.PriorityQueue.siftUp(Unknown Source)
at java.util.PriorityQueue.offer(Unknown Source)
at PriorityQueueTest.<init>(PriorityQueueTest.java:10 )
at PriorityQueueTest.main(PriorityQueueTest.java:24)
however, when i use Stack<Number> a = new Stack<Number>(); i could add all the Double, Integer and Float. So what's the diference between them? how can i figure out the difference in api doc?Last edited by oszc; 10-06-2011 at 01:50 PM.
- 10-06-2011, 02:26 PM #2
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,406
- Blog Entries
- 7
- Rep Power
- 17
Re: difference of add method between Queue class and Stack class
Stacks and Queues can store objects only so autoboxing is applied when you attempt to store primitives (ints, longs etc.) A Queue needs its members to implement the Comparable interface because it has to store the members in a certain order; a Stack doesn't do that. The Number, Integer, Double etc. hierarchy is a bit stupid: Integers can only be compared to Integers, Doubles to Doubles etc. You put Integers and Doubles in your Queue and tries to compare them. You saw the result in your stack trace. A cheap hack would be to store doubles in your Queue only.
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
super class reference variable accesses overriding sub class method
By subith86 in forum New To JavaReplies: 5Last Post: 01-26-2011, 06:38 PM -
how call from inner class(anonymous or not), a method of parent class?
By lse123 in forum AWT / SwingReplies: 2Last Post: 05-01-2010, 08:59 AM -
Nested List class for Simulation Queue
By Cheddz in forum Advanced JavaReplies: 2Last Post: 02-19-2010, 01:19 AM -
Child-Class Calling a Method in a Parent-Class
By Blah_ in forum New To JavaReplies: 5Last Post: 09-29-2009, 02:48 AM -
Difference between Abstract class having only abstract method and a Interface class
By Santoshbk in forum New To JavaReplies: 6Last Post: 02-11-2009, 10:51 AM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks