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

PriorityQueue returns values in incorrect order for 3-element queue

XMLWordPrintable

      ADDITIONAL SYSTEM INFORMATION :
      Linux Mint 19.1 64bit
      openjdk 11.0.3 2019-04-16
      OpenJDK Runtime Environment (build 11.0.3+7-Ubuntu-1ubuntu218.04.1)
      OpenJDK 64-Bit Server VM (build 11.0.3+7-Ubuntu-1ubuntu218.04.1, mixed mode, sharing)


      A DESCRIPTION OF THE PROBLEM :
      I created an instance of PriorityQueue using the constructor accepting an Comparator instance (created with help of Comparator.comparingInt method). Then I added elements with decreasing int value that is used by aforementioned comparingInt.

      In cases, where queue has exactly 3 elements, the order returned by iterator is incorrect. Strangely enough, when elements are added in ascending order, returned sequence is actually correct. For queues of 4 elements (or bigger) it seems, like order is always correct.

      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Run the code below

      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      1
      2
      3
      ACTUAL -
      3
      2
      1

      ---------- BEGIN SOURCE ----------
      import java.util.Comparator;
      import java.util.PriorityQueue;

      public class Queue3 {

          static class Pri {
              int pri;

              public Pri(int pri) {
                  this.pri = pri;
              }

              public int pri() {
                  return pri;
              }
          }

          public static void main(String[] args) {
              PriorityQueue<Pri> queue = new PriorityQueue<Three.Pri>(Comparator.comparingInt(Pri::pri));
              queue.add(new Pri(3));
              queue.add(new Pri(2));
              queue.add(new Pri(1));
              queue.forEach(p -> System.out.println(p.pri));
          }
      }

      ---------- END SOURCE ----------

      FREQUENCY : always


            psonal Pallavi Sonal (Inactive)
            webbuggrp Webbug Group
            Votes:
            0 Vote for this issue
            Watchers:
            2 Start watching this issue

              Created:
              Updated:
              Resolved: