问题
I tried to create an interface 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.
回答1:
<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);
}
}
回答2:
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.
回答3:
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.
来源:https://stackoverflow.com/questions/7131714/java-recursive-generic-type-definitions