Reputation: 5587
I want to have the following method not show a warning about using raw types, but I can't figure out the syntax to tell it to do what I want. Here is the current method:
static long countSplitInversions(List<? extends Comparable> list) {
long inversions = 0;
final int leftLimit = list.size() / 2;
int left = 0;
int right = leftLimit;
for (int i = 0; i < list.size(); i++) {
if (left == leftLimit || right == list.size()) {
break;
}
if (list.get(left).compareTo(list.get(right)) <= 0) {
left++;
} else {
right++;
inversions += leftLimit - left;
}
}
return inversions;
}
When I change the signature to avoid the warning to:
static <T> long countSplitInversions(List<? extends Comparable<? super T>> list)
then the line where the compareTo is won't compile with the error:
Method compareTo in interface java.lang.Comparable<T> cannot be applied to given tyes
required: capture #1 of ? super T
found: java.lang.Comparable<? super T>
Upvotes: 1
Views: 511
Reputation: 285405
Consider changing your method signature to something like...
static <T extends Comparable<? super T>> long countSplitInversions(List<T> list) {
Upvotes: 4
Reputation: 78589
Do you mean a warning or compiler error?
You current code already produces a warning, but if you mean a compiler error, as you suggest at the end, then you need to specify a type argument for your Comparable bound.
Somewhat like this will generate a compiler error as you suggest.
static long countSplitInversions(List<? extends Comparable<?>> list) {
/ /...
}
But that would be pointless, you could do nothing with your comparable objects.
As such you may need a type parameter for your method, as the other answer suggest.
Upvotes: 1