You who read me now: I am studying for the SCJP and ran across a problem i can not figure out (yes, this was the only one... lol). The issue has to do with Collections found in java's util class. My problem, in the most general sense, is I do not understand the output...
(Taken from question 9 in the Chapter 7 self-exam)
9. Given the proper import statement(s), and The code:
The output is: 2 2 3 4
I put the code inside a class with a main method and ran it and obtained the output as shown in the answers section of the great-most-excellent SCJP book by Bates and Sierra (2008).
However, I am COMPLETELY BAFFLED as to how for instance the peek() method on line 16 produces 2 instead of 4? I know that peek returns the highest number and I am not sure how this works with string representations of numbers as opposed to actual primitive types like integer, long, short, double, float, etc.
From the API of PriorityQue on the peek method:peek()
Retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.
The natural order for numeric types would be ascending order of magnitude(lowest value comes first). For string representations of numbers, it is slightly different.
Ordering of PriorityQueue<Integer>:1,2,4,33
Ordering of PriorityQueue<String>:1,2,33,4 -->First character '3' in '33' sorts before '4'
Verify the ordering by
Oh man... I can't believe it is the same order basically with integer representations of Strings as it is for integers. Thank you for supplying the code, that helped me understand. I obviously did not grasp how each method actually behaves. I was surprised it printed the entire PriorityQue instead of printing and removing the head of the que.
Thank you for explaining this further. I had to study Sebanti Sanyal's response to understand that peek in this case returns the first element and not the largest number. Thank you again for driving this point home, as the expression goes.
subject: Natural Ordering with PriorityQue and String representations of integers