Problem
new PriorityQueue<>(List.of(new Object())) succeeds today when it should throw 
ClassCastException. initFromCollection relies on heapify() to surface 
incomparable elements, but heapify performs no comparisons on a singleton, so 
the lone element is never validated. Collections with two or more 
non-Comparable elements already throw.

Fix
In initFromCollection, when the collection holds exactly one element and no 
comparator is in play, self-compare the element before heapifying. This mirrors 
what TreeMap does for its first key (see JDK-5045147). Behavior with an 
explicit comparator is unchanged: non-Comparable elements are still accepted 
when a comparator is provided.

Testing
Added a copyConstructorSingleton regression test to AddNonComparable covering 
PriorityQueue(Collection) and PriorityQueue(Collection, Comparator) with a null 
comparator, plus the positive cases (Comparable singleton, explicit 
comparator). Verified the new test passes against the patched class and the 
existing queues() test still passes.


Please let me know for further questions 


---------
- [x] I confirm that I make this contribution in accordance with the [OpenJDK 
Interim AI Policy](https://openjdk.org/legal/ai).

-------------

Commit messages:
 - 8390157: (coll) PriorityQueue copy constructors accept non-Comparable 
single-element collection

Changes: https://git.openjdk.org/jdk/pull/32966/files
  Webrev: https://webrevs.openjdk.org/?repo=jdk&pr=32966&range=00
  Issue: https://bugs.openjdk.org/browse/JDK-8390157
  Stats: 28 lines in 2 files changed: 27 ins; 0 del; 1 mod
  Patch: https://git.openjdk.org/jdk/pull/32966.diff
  Fetch: git fetch https://git.openjdk.org/jdk.git pull/32966/head:pull/32966

PR: https://git.openjdk.org/jdk/pull/32966

Reply via email to