Java - recursive generic type definitions
I tried to create an inter开发者_如何转开发face ISortableStack
using <E extends comparable <E>>
but I can't move forward. What does the following do?
<E extends Comparable<E>>
I've tried this, but it doesn't help.
<E extends Comparable<E>>
means that E
must be a type that knows how to compare to itself, hence, the recursive type definition.
public class Comparables {
static class User implements Comparable<User> {
@Override
public int compareTo(User user) {
return 0;
}
}
/**
* This class cannot be used with Collections.sort because an
* UncomparableUser is not comparable with itself. However, notice
* that you get no compiler error just for implementing
* Comparable<String>.
*/
static class UncomparableUser implements Comparable<String> {
@Override
public int compareTo(String user) {
return 0;
}
}
public static void main(String[] args) {
List<User> users = Arrays.asList(new User());
// Using this would cause a compiler error
// List<UncomparableUser> users = Arrays.asList(new UncomparableUser());
Collections.sort(users);
}
}
If you're asking what does this mean:
<E extends Comparable<E>>
It means that the class 'E' passed in must implement the Comparable
interface.
The <
and >
characters are part of the "generic" syntax. The standard library is choke full of "generic" interfaces; take a look at the Set
interface for an example.
精彩评论