5

I have a simple question. I am implementing PriorityQueue in my project. My question is can i set a fixed size for PriorityQueue is Java ?

MaxZoom
  • 7,619
  • 5
  • 28
  • 44
medo0070
  • 511
  • 1
  • 5
  • 21
  • 3
    No. This is part of `Collection` which grow dynamically based on items we put/add. Better use something like arrays if you are looking for fixed size or write custom implementation. – kosa Jun 22 '15 at 19:54
  • 1
    How would you expect the semantics of that to work? – Louis Wasserman Jun 22 '15 at 20:02
  • 1
    (If you're just trying to get the top k elements of a particular collection, and you can use third-party libraries, consider using Guava's `Optional.leastOf`/`greatestOf`, which have significantly better performance than using a `PriorityQueue`.) – Louis Wasserman Jun 22 '15 at 20:03
  • 1
    @MaxZoom No. Please don't do that. `MinMaxPriorityQueue` is intended to be used only when you actually need to access both the minimum and the maximum element, and will perform poorly for the case you're describing. _Do not_ use `MinMaxPriorityQueue` for that case. – Louis Wasserman Jun 22 '15 at 20:09

1 Answers1

7

As the oracle documentation here states, http://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html:

A priority queue is unbounded, but has an internal capacity governing the size of an array used to store the elements on the queue. It is always at least as large as the queue size. As elements are added to a priority queue, its capacity grows automatically. The details of the growth policy are not specified.

A possible workaround may be that you can check the size before performing any operation:

if (q.size() <= QUEUE_LIMIT)
     //your code
Amita
  • 944
  • 1
  • 8
  • 20