RFR: 6356745: Introduce constructor for PriorityQueue with existing collection and custom comparator
Valeh Hajiyev
duke at openjdk.org
Thu Dec 14 20:30:45 UTC 2023
This commit addresses the current limitation in the `PriorityQueue` implementation, which lacks a constructor to efficiently create a priority queue with a custom comparator and an existing collection. In order to create such a queue, we currently need to initialize a new queue with custom comparator, and after that populate the queue using `addAll()` method, which in the background calls `add()` method (which takes `O(logn)` time) for each element of the collection (`n` times). This is resulting in an overall time complexity of `O(nlogn)`.
PriorityQueue<String> pq = new PriorityQueue<>(customComparator);
pq.addAll(existingCollection);
The pull request introduces a new constructor to streamline this process and reduce the time complexity to `O(n)`. If you create the queue above using the new constructor, the contents of the collection will be copied (which takes `O(n)` time) and then later `heapify()` operation (Floyd's algorithm) will be called once (another `O(n)` time). Overall the operation will be reduced from `O(nlogn)` to `O(2n)` -> `O(n)` time.
PriorityQueue<String> pq = new PriorityQueue<>(existingCollection, customComparator);
-------------
Commit messages:
- fix styling
- Introduce constructor for PriorityQueue with existing collection and custom comparator
Changes: https://git.openjdk.org/jdk/pull/17045/files
Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=17045&range=00
Issue: https://bugs.openjdk.org/browse/JDK-6356745
Stats: 19 lines in 1 file changed: 19 ins; 0 del; 0 mod
Patch: https://git.openjdk.org/jdk/pull/17045.diff
Fetch: git fetch https://git.openjdk.org/jdk.git pull/17045/head:pull/17045
PR: https://git.openjdk.org/jdk/pull/17045
More information about the core-libs-dev
mailing list