Java generics with multiple parameters

I've seen examples on the website dealing with generics with multiple parameters, but none of them apply to me

So this is a deal: I'm trying to learn java generics and decided to create a simple binary array search utility function I'm testing with custom objects and integers For feedback on errors and warnings, I'm using eclipse This 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,start,mid - 1);
    } else {
        return mid;
    }
}

So obviously I got a warning from raw types that generics should be parameterized If I have multiple parameters that need to be of the same type, how can I do this correctly?

solution

The following is a working solution using generics and correct parameter checking:

public static <T extends Comparable<? super T>> int binarySearch(T[] array,T item,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,mid - 1);
    } else {
        return mid;
    }
}

Solution

You can specify function specific generic parameters like this

public static <T extends Comparable<? super T>> int binarySearch(T[] arr,T elem,int end){
    //...
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>