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:
private Location findFirst(E item) {
Location current;
int closestMatchArray1;
int closestMatchArray2;
Object[] firstItemInArray2 = new Object[numArrayInUse];
Object firstItem;
Comparator<E> comparator = new CompareElement();
for (int i - 0; i < numArrayInUse; i++) {
firstItem = topArray[i];
firstItemInArray2[i] = firstItem;
}
closestMatchArray1 = Arrays.binarySearch(firstItemInArray2, item, comparator);
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:
public class CompareElement implements Comparator<E> {
public int compare(E firstItem, E secondItem) {
return firstItem.compareTo(secondItem);
}
}
E?compareTois a method fromComparable. In yourCompareElementclass,Emust be declared, i.e.public class CompareElement<E extends Comparable> implements Comparator<E>