Reputation: 1559
1.I thought that Interfaces in Java don't have implementations, so how can I use my compareTo() here?
2.As far as I knew the extends keyword can add new methods to an interface in order to be implemented later. So I don't understand what/how am I exactly extending right here ?
Thanks
public class Compare {
// simple comparison operator < > ... works only on primitives
// that's why we need the Comparable
public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {
int count = 0;
for (T e : anArray)
if (e.compareTo(elem) > 0)
++count;
return count;
}
}
Upvotes: 0
Views: 153
Reputation: 4185
Actually from Java 8 onwards, Interfaces can have (default, partial) implementation, but that's an aside. The confusing thing here is that the keyword extends
has two usages:
List<T extends Comparable>
. Using the same key word was a decision made when they introduced this, presumably to emphasise how the kind of class that is suitable for this Generic T
would itself have to extend Comparable
(for example). As classes and interfaces in Java share the same hierarchies, it doesn't really matter which you use here (though interfaces are advisable). Upvotes: 0
Reputation: 22631
Interfaces in Java don't have implementations, but you can't create an instance of an interface. (Try it - what happens when you include new List()
in your code?) You can only create an instance of a class implementing that interface, and the class is required to implement the interface's methods.
In this case, you're not extending anything at all yourself. You just indicate 'this method can only be used for classes T
which extend/implement the Comparable<T>
interface'.
Upvotes: 1