Search code examples
javagenericscomparable

Java generics with multiple parameters


I have seen examples on the site that deal with generics with multiple parameters but none that work for my situation.

So here is the deal: I am trying to learn Java generics and have decided to create a simple binary array search utility function. I am testing it out using custom objects and integers. To get feedback on errors and warning I am using Eclipse. Here is what I have:

public static int binarySearch(Comparable[] array, Comparable item, int start, int end) {
    if(end < start) {
        return -1;
    }
    int mid = (start + end) / 2;
    if(item.compareTo(array[mid]) > 0) {
        return binarySearch(array, item, mid + 1, end);
    } else if(item.compareTo(array[mid]) < 0) {
        return binarySearch(array, item, start, mid - 1);
    } else {
        return mid;
    }
}

So obviously I get the warnings for Raw types saying the generics should be parameterized. How can I do this correctly given that I have multiple parameters which both need to be the same type?

SOLUTION

Here is the working solution using generics with the correct parameter checks:

public static <T extends Comparable<? super T>> int binarySearch(T[] array, T item, int start, int end) {
    if(array.length == 0) {
        return -1;
    }
    if(item == null) {
        return -1;
    }
    if(start < 0) {
        return -1;
    }
    if(end < start) {
        return -1;
    }
    int mid = (start + end) / 2;
    if(item.compareTo(array[mid]) > 0) {
        return binarySearch(array, item, mid + 1, end);
    } else if(item.compareTo(array[mid]) < 0) {
        return binarySearch(array, item, start, mid - 1);
    } else {
        return mid;
    }
}

Solution

  • you can specify function-specific generic parameter like so

    public static <T extends Comparable<? super T>> int binarySearch(T[] arr,T elem,int start,int end){
        //...
    }