title: Binary search on arrays/comparator using generics Java
body: <p>I'm struggling to make a comparator for binary search work on an array of objects. Essentially the goal is to search a ragged array to find the first match of an item OR the closest match to provide an insert point. The method passes in an generic (this is unchangeable - as this is homework) but you can't create arrays of generic types... so, my comparator is throwing an error: "The method binarySearch(Object[], Object) in type Arrays is not applicable for the arguments (Object[], E, Comparator)". Perhaps I need to cast the generic element "item"? I'm not sure. Code:</p>
  
  <pre><code>private Location findFirst(E item) {
      Location current;
      int closestMatchArray1;
      int closestMatchArray2;
  
  Object[] firstItemInArray2 = new Object[numArrayInUse];
  Object firstItem;
  
  Comparator&lt;E&gt; comparator = new CompareElement();
  
  for (int i - 0; i &lt; numArrayInUse; i++) {
      firstItem = topArray[i];
      firstItemInArray2[i] = firstItem;
  }
  
  closestMatchArray1 = Arrays.binarySearch(firstItemInArray2, item, comparator);
  </code></pre>
  
  <p>Secondary, but related question. In the comparator, I am attempting to invoke the Comparable method "compareTo" to obtain a negative integer that gives an approximate location for where an item would be if it were in the array on a failed search, but again, I'm having trouble with generics, getting this error: "The method compareTo(E) is undefined for the type E". Code:</p>
  
  <pre><code>public class CompareElement implements Comparator&lt;E&gt; {
    public int compare(E firstItem, E secondItem) {
       return firstItem.compareTo(secondItem);
    }
  }
  </code></pre>