I use PriorityQueue for partial sorting of some data. In particular, this is the code:
Collection<Data> data = ...;
PriorityQueue<Data> queue = new PriorityQueue<Data>(data.size(), dataComparator);
queue.addAll(data);
// iterate over queue with remove() until we have as much data as we need or until queue is empty
Unfortunately, when data collection is empty, the code fails, because PriorityQueue cannot be passed zero as initialCapacity. What are reasons behind this design decision? Why can’t there be an 0-sized PriorityQueue?
UPD: I know how to work around this. I’d like to know why doesn’t PriorityQueue include this max(1, n) code inside it – are there any reasons or is it just a bad API design?
Why do you want to use a queue? A queue is a data structure made for the case where you have a “producer” which enqueues items, and a “consumer” which dequeues them. A priority queue orders the enqueued items using a tree structure. A buffer is needed for a producer being able to enqueue, so
initialCapacity = 0makes no sense.In your case you never enqueue anything, you just process data from a collection you already have. Why create a new data structure for it? You could just use
or, following Daniel’s comment, use the Selection Algorithm so you can profit from your situation that you actually only need a subset of your items.