On Mon, 19 Oct 2026 16:39:36 GMT, Srikanth Palutla <[email protected]> wrote:

>> 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).
>
> Srikanth Palutla has updated the pull request incrementally with one 
> additional commit since the last revision:
> 
>   Move singleton Comparable check into initElementsFromCollection

src/java.base/share/classes/java/util/PriorityQueue.java line 304:

> 302:             Comparable<? super E> e = (Comparable<? super E>) es[0];
> 303:             e.compareTo((E) es[0]);
> 304:         }

Wouldn't it be sufficient to say:

if (len == 1 && this.comparator == null && !(es[0] instanceof Comparable))
    throw new ClassCastException("class " + es[0].getClass().getName() + " 
cannot be cast to " + Comparable.getClass().getName());

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

PR Review Comment: https://git.openjdk.org/jdk/pull/32966#discussion_r4317186545

Reply via email to