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

PriorityQueue copy constructors can lead to heap pollution

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Open
    • Priority: P4
    • Resolution: Unresolved
    • Affects Version/s: None
    • Fix Version/s: tbd
    • Component/s: core-libs
    • Labels:
      None

      Description

      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 simliar 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.

        Attachments

          Activity

            People

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

              Dates

              Created:
              Updated: