Reputation: 685
I have defined an array which can hold element of generic type. Now I am comparing the array[index] with another comparable element. Below is the code snippet.
I have defined an array which can hold element of generic type. Now I am comparing the array[index] with another comparable element. Below is the code snippet.
public class Test {
void methodArr(){
final Comparable[] arr = { 1, 2, 3, 4, 5};
Integer item = 10;
compare(arr, item);
}
private int compare(Comparable<?>[] arr, Comparable<?> item) {
return arr[0].compareTo(item); //Error in this line
}
}
Now it gives the error in the method compare() at
arr[0].compareTo(item)
And the error is:
The method compareTo(capture#1-of ?) in the type comparable is not applicable for the arguments (Comparable)
I don't understand where am I making mistake? My object is the method compare() should take an array as element of type comparable.
Upvotes: 2
Views: 5762
Reputation: 106400
Comparable<?>
means that you don't know what kind of Comparable
you're getting; you could be getting Comparable<Object>
, which doesn't work unless you explicitly override compareTo
for that instance of Object
.
The correct solution to this is to introduce a type parameter to the method such that the type you care about is bound to Comparable
.
private <T extends Comparable<T>> int compare(T[] arr, T item) {
return arr[0].compareTo(item);
}
The above will still work with a Comparable[]
, not a Comparable<?>[]
. Generics and arrays don't mix very well, so where you can, try to avoid combining the two.
If you want to avoid the unchecked warnings (which at this point can be safely ignored due to array covariance),then you would modify the signature of your methodArr
method to accept a similar bound.
<T extends Comparable<T>> void methodArr(final T[] arr, T item) {
// use the passed-in arr and item variables instead.
}
Upvotes: 2
Reputation: 1205
A simple
private <T extends Comparable> int compare(T[] arr, T item) {
return arr[0].compareTo(item);
}
Upvotes: -1
Reputation: 140319
There is no relationship between the two wildcards in your parameters. Instead you should specify that they are the same type using an explicit type variable:
private <T extends Comparable<T>> int compare(T[] arr, T item) {
Upvotes: 1