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;
}
}
A Generic class can have muliple type parameters.
As with generic methods, the type parameter section of a generic class can have one or more type parameters separated by commas. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.
A type parameter can have multiple bounds.
To use Java generics effectively, you must consider the following restrictions: Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters. Cannot Declare Static Fields Whose Types are Type Parameters.
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){
//...
}
This is the typical way to create generic functions:
public static <T extends Comparable<? super T>> int binarySearch(T[] array, T item, int start, int end) { ... }
For extra generality, item
doesn't have to be of the same type the things in the array are, and things in the array don't have to be Comparable
since you're not comparing them to anything, so
public static <T> int binarySearch(T[] array, Comparable<T> item, int start, int end) { ... }
gives some additional flexibility.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With