Multiple Parameter Java Generators

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; } } 
+6
source share
2 answers

you can specify a common general parameter for the function

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

This is a typical way to create common functions:

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

For more generality, item does not have to be of the same type as things in the array, and things in the array should not be Comparable , since you are not comparing them to anything, therefore

 public static <T> int binarySearch(T[] array, Comparable<T> item, int start, int end) { ... } 

gives extra flexibility.

+5
source

Source: https://habr.com/ru/post/915046/


All Articles