56
21
|
In Java there are
SortedSet and SortedMap . Both belongs to collections and provided a sorted way to access the elements.
However, there is no
SortedList in Java, in my understanding. You can usejava.util.Collections.sort() to sort a list.
Any idea why it is designed like that?
The Sun has provided the
TreeSet and the TreeMap and but no TreeList. They provided a utilityCollections.sort() to sort the List. When they provided the Sorted Map and Set, what is the reason they didn't provide the Sorted List.?
Is there any specific reason behind it.?
I am preparing for SCJP, so while going through the
Generics and Collections , I got this doubt. can anyone clarify. | ||||||||||||||||
|
115
|
List iterators guarantee first and foremost that you get the list's elements in the internal order of the list (aka. insertion order). More specifically it is in the order you've inserted the elements or on how you've manipulated the list. Sorting can be seen as a manipulation of the data structure, and there are several ways to sort the list.
I'll order the ways in the order of usefulness as I personally see it:
1. Consider using a
|
|
+1. Imo, this is more constructive than the top voted answer. It comes with two minor downsides though. The PriorityQueue does not support random access. You cannot do peek(elementIndex). So you cannot do e.g.
Integer maxVal = prioQueue.peek(prioQueue.size() - 1); . Secondly if you're intending to use the PriorityQueue simply as a sorted list, it will sound less intuitive to see PriorityQueue in the code than it would have been to see SortedList , if such a data structure existed. – Alderath Jan 4 '12 at 12:18 | ||
|
And, after looking at the other question which someone linked in the comments, another big disadvantageis that the iterator of PriorityQueue is not guaranteed to return elements in any specific order. So, unless I am overlooking something, the only way to e.g. print all objects in the PriorityQueue in order is to repeatedly poll() the queue until it is empty. To me, this feels borderline retarted. To print the objects in a PriorityQueue twice, you'd first have to copy the PriorityQueue and then poll() all objects from the original PriorityQueue and then pol()l all objects from the copy. – Alderath Jan 4 '12 at 12:49
| ||
Hmm... looks like you're right Alderath. You can't use the iterator of PriorityQueue to get the elements in expected order. Looks like I have to edit my answer. – Spoike Jan 4 '12 at 13:10
| |||
|
Priority queue is just a heap, you can access only the top, imo it does not belong to the answer of the question. – bestsss Jan 4 '12 at 17:25
|