title: java Collections.binarySearch() returning -2
body: <p>I have a text file which contains student information. I sort this information using the comparator class which implements the <code>comparator</code> interface.This sorts fine fine when calling <code>Collection.Sort();</code></p>
  
  <p>I then use the <code>comparator</code> in the <code>binarySearch()</code> method.  I have an int index that returns the index of the binary search. after debugging it seems that the <code>binarySearch()</code> isnt sorting the data properly because I get an index of 0 for 501 which is correct, an index of 1 for 503 which is incorrect and an index of -2 for 502. Is the <code>binarySearch</code> not using the comparator apppropriately and thus not sorting the data appropriately as its returning the data in its original form.</p>
  
  <pre><code> =================================================
      First Name: Mark
      Last Name: Evans
      Registration: 501
  
      Subject: Maths
      Assignment: 1
      Homewok Mark: 70
      Exam Mark: 80
  
      Assignment: 2
      Homewok Mark: 70
      Exam Mark: 40
  
      Subject: English
      Assignment: 1
      Homewok Mark: 40
      Exam Mark: 50
  
      Assignment: 2
      Homewok Mark: 60
      Exam Mark: 70
  
      Subject: Science
      Assignment: 1
      Homewok Mark: 50
      Exam Mark: 60
  
      Assignment: 2
      Homewok Mark: 80
      Exam Mark: 45
  
      Assignment: 3
      Homewok Mark: 67
      Exam Mark: 47
  
      Assignment: 4
      Homewok Mark: 38
      Exam Mark: 57
  
      =================================================
      First Name: Linda
      Last Name: Evans
      Registration: 503
  
      Subject: Maths
      Assignment: 1
      Homewok Mark: 50
      Exam Mark: 60
  
      Assignment: 2
      Homewok Mark: 70
      Exam Mark: 50
  
      =================================================
      First Name: Joseph
      Last Name: Evanw
      Registration: 502
  
      Subject: English
      Assignment: 1
      Homewok Mark: 40
      Exam Mark: 50
  </code></pre>
  
  <p>I have a comparator class that works fine and sorts the data appropriately.</p>
  
  <pre><code>public class StudentComparator implements Comparator&lt;Student&gt; {
  
      @Override
      public int compare(Student s1, Student s2) {
  
          int registrationNumber1 = s1.getRegistrationNumber();
          int registrationNumber12 = s2.getRegistrationNumber();
  
          return registrationNumber1 - registrationNumber12;
      }
  
  }
  
  
  public void searchStudentByName() {
  
          int number = 503;
          int subjectNumber = 1;
  
          int index = Collections.binarySearch(studentList, new Student(number),
                  new StudentComparator());
          for (int i = 0; studentList.size() &gt; i; i++) {
              if (i == index) {
  
                  System.out.print(studentList.get(i));
  
              }
          }
  
      }
  </code></pre>