通用接口 - Java
如果我有以下代码:
public interface BinaryTree<T extends Comparable<? super T>>{}
这意味着它是一个接受实现 Comparable 的对象的接口,对吧? 是什么意思?
接下来,如果我想编写 BinaryTree
的实现 班级减速应该是什么样子?
If I have the following code:
public interface BinaryTree<T extends Comparable<? super T>>{}
It means that it's an interface that accepts object that implement Comparable
right?
What does <?Super T>
means?
And the next thing, If I want to write an implementation to BinaryTree
How should the class deceleration look like?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
<代码> 表示“T 的任何超类(或超级接口)”(@GETah 引用了文档。)
因此,您的类将类似于 public class MyBinaryTree
public class MyBinaryTree< T 扩展了 Comparable>实现 BinaryTree{...}
- 您需要指定 MyBinaryTree 的通用参数以与接口所需的兼容。<? super T>
means "any superclass (or superinterface) of T" (as @GETah has quoted the docs.)So, your class will look something like
public class MyBinaryTree<T extends Comparable<? super T>> implements BinaryTree<T> {...}
- you need to specify the generic parameter of MyBinaryTree to be compatible with that required by the interface.Java 定义了“?”成为未知类型。
对于泛型类型 G,类型实例 G 是
所有其他类型实例的超类型。
未知类型的变量不能被赋值,并且
读取时被视为对象。
例如打印整个集合:
这是有效的,因为 Collection 是所有集合的超类型。
未知类型的祖先,标记为
G
,允许读取未知类型的实例。未知类型的后代,标记为
G
,允许写入未知类型的实例。Java defines “?” to be the Unknown Type.
For a generic type G, the type instance G is the
super-type of all other type instances.
Variables of the unknown type cannot be assigned to, and are
considered as Object when reading from.
For example printing an entire collection:
This works because Collection is the super-type of all collections.
The ancestor of the unknown type, marked
G<? extends X>
, allows to read an instance of the unknown type.The descendant of the unknown type, marked
G<? super Y>
, allows to write to an instance of the unknown type.BinaryTree
采用类型参数,并且该类型参数必须是与其自身实例或其超类之一Comparable
的类。假设您有一个类
Frobgit
,它被声明为implements Comparable
,那么这将是BinaryTree
的有效类型参数。如果它被声明为implements Comparable
BinaryTree
必须比较存储在其中的对象,这确保了它能够这样做。BinaryTree
takes a type parameter, and the type parameter has to be a class which isComparable
with instances of itself, or one of its superclasses.So say if you have a class
Frobgit
, which is declared asimplements Comparable<Frobgit>
, that would be a valid type parameter forBinaryTree
. If it was declared asimplements Comparable<Object>
, that would also be OK.A
BinaryTree
has to compare the objects which are stored in it, and this ensures that it is able to do so.对于
,文档说:
For the
<? super T>
, the documentation says: