title: How do you implement a binary search for object arrays in a general program?
body: <p>So, I am in a course to learn java, and I'm learning about sorting, searching, algorithms, and generics. I am trying to recreate a binary search method/class that accepts any type of <code>Comparable</code> object (like the ArrayList&lt;<em>Type</em>>).</p>
  
  <p>I understand how to do it with <code>int</code>s, but I dont really know how to go about it with non-primitive types.
  This is what I assume it should roughly look like:</p>
  
  <pre><code>public class Objects&lt;T&gt; implements Comparable //I'm not sure about this,
  //but I need to call compareTo() to compare the objects?
  {
      /**
       * called from other program to find an element index in an array
       */
      public static int binSearchAll(T find, T array[])
      {
          return binarySearch(array, 0, (array.length)-1, find);
      }
  
      public static int binarySearch(T array[], int lower, int upper, T X)
      //x is the element to find
      {
          if (upper &lt; lower)
              return -1;
          int middle = (lower + upper) / 2;
          if (array[middle].compareTo(X))
              return middle;
          if (array[middle] &lt; X)
              return binarySearch(a, middle+1, upper, X);
          else
              return binarySearch(a, lower, middle-1, X);
      }
  }
  </code></pre>
  
  <p>I tried to figure out how to make this work, but I'm at a loss. In the <code>int</code> version, it works, but then it's only for <code>integer</code> types and doesn't accept <code>double</code> or <code>string</code> types as the problem asks.</p>
  
  <p>in the driver class, I want to be able to create a new object and use it like this:</p>
  
  <pre><code>String[] str = {"a", "b", "c"};
  Objects&lt;String&gt; s = new Objects&lt;String&gt;();
  int indexOfB = s.binSearchAll("b", str);
  </code></pre>
  
  <p>or, if it's possible, like this:</p>
  
  <pre><code>String[] str = {"a", "b", "c"};
  int indexOfB = Object&lt;String&gt;.binSearchAll("b", str);
  </code></pre>
  
  <p>The exact wording of the problem is:</p>
  
  <blockquote>
    <p>Create an ObjectBinarySearcher class that can search an array of Comparable objects.
    Demonstrate the class in a program that searches for a String in an array of String
    objects.</p>
  </blockquote>
  
  <p>I'm almost sure I'm overthinking this.</p>
  
  <p>Thanks for any help you can give!</p>