Reputation: 103
class GenMethDemo {
// Determine if an object is in an array.
static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
for(int i=0; i < y.length; i++)
if(x.equals(y[i])) return true;
}
}
how can Comparable interface be extended rather than being implemented being an Interface itself?
Upvotes: 2
Views: 378
Reputation: 10127
The meaning of extends
within < ... >
is a little different from its
normal meaning (like in class FileInputStream extends InputStream
).
Quoted from the tutorial Upper Bounded Wildcards:
To declare an upper-bounded wildcard, use the wildcard character (
?
), followed by theextends
keyword, followed by its upper bound. Note that, in this context,extends
is used in a general sense to mean either "extends" (as in classes) or "implements" (as in interfaces).
Upvotes: 0
Reputation: 393811
The Comparable
interface is not extended here.
<T extends Comparable<T>, V extends T>
are generic type parameters with type bounds. It means that the isIn
method has two generic type parameters - one of them is called T
and must implement Comparable<T>
, and the other is called V
, and must be a sub-type of T
.
BTW, your specific method doesn't require V
and T
to implement Comparable
, since it doesn't call compareTo
.
However, it would be required if you changed the code to:
static <T extends Comparable<T>, V extends T> boolean isIn(T x, V[] y) {
for(int i=0; i < y.length; i++)
if(x.compareTo(y[i]) == 0) return true;
return false;
}
Then you can call this method only with parameters that implement Comparable
.
For example:
if (isIn ("str",new String[]{"a","b","c"})) {
}
Upvotes: 3