I saw examples on the site that relate to generics with several parameters, but none of them work for my situation.
So here's the deal: I'm trying to learn Java generators and decided to create a simple binary array lookup function. I am testing it with custom objects and integers. To get feedback on errors and warnings, I use 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; } }
Therefore, obviously, I am getting warnings for Raw types saying that generics should be parameterized. How can I do this correctly, given that I have several parameters that must be of the same type?
Decision
Here is a working solution using generics with the right 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; } }