Uploaded image for project: 'JDK'
  1. JDK
  2. JDK-8263475

PriorityQueue copy constructors can lead to heap pollution

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: P4 P4
    • tbd
    • 5.0
    • core-libs
    • None

      Consider:

      var pq = new PriorityQueue<Number>(new TreeSet<>(Integer::compare))
      pq.addAll(Arrays.asList(1.0, 2.0))
      ==> ClassCastException

      The problem is that the copy constructor used above takes a SortedSet<? extends E> which allows the PQ type arg to be a supertype of the SortedSet's type arg. However, the constructor then does

      this.comparator = (Comparator<? super E>) c.comparator();

      The arg's comparator is Comparator<Integer> but this casts it to Comparator<? super Number> which is clearly unsafe. (Unchecked warnings are suppressed for this entire class.)

      A similar problem can occur in the copy constructor that takes a Collection; in that case an instanceof/downcast to SortedSet is performed before the comparator is fetched; the latter is also unsafe.

            smarks Stuart Marks
            smarks Stuart Marks
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated: