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

Arrays.binarySearch returns a value beyond toIndex when doc says it will return toIndex or less

XMLWordPrintable

    • x86_64
    • linux

      FULL PRODUCT VERSION :
      openjdk version "1.8.0_151"
      OpenJDK Runtime Environment (build 1.8.0_151-b12)
      OpenJDK 64-Bit Server VM (build 25.151-b12, mixed mode)


      ADDITIONAL OS VERSION INFORMATION :
      Fedora 26 64Bit

      A DESCRIPTION OF THE PROBLEM :
      Occurs when the value is not found in the array and the insertion point is toIndex (new value is greater than all values in array)

      for binarySearch on a range of an array the javadoc says>(-(insertion point) - 1) but the code returns>
      -(low + 1);



      STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
      Example of bug>
      Source Array>
      [12, 131081, 327681, 327682, 327683, 327684, 327685, 327686, 327687, 327688, 327689, 327690, 0]

      method call>
      Arrays.binarySearch(source,1,12,327691);



      EXPECTED VERSUS ACTUAL BEHAVIOR :
      EXPECTED -
      It should return 12 to comply with doc which says that ", or toIndex if all elements in the range are less than the specified key"

      Both the javadoc and code are wrong in this example


      ACTUAL -
      the code returns 13 due to>
      return -(low + 1); //line 1922

      ERROR MESSAGES/STACK TRACES THAT OCCUR :
      no error message

      REPRODUCIBILITY :
      This bug can be reproduced often.

      ---------- BEGIN SOURCE ----------
      int[] source = new int[] {12, 131081, 327681, 327682, 327683, 327684, 327685, 327686, 327687, 327688, 327689, 327690, 0};

      System.out.println(Arrays.binarySearch(source,1,12,327691));
      ---------- END SOURCE ----------

      CUSTOMER SUBMITTED WORKAROUND :
      return -(low) //not tested fully in all combos

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

              Created:
              Updated:
              Resolved: