在Java中泛型的扩展 [英] implements vs extends in generics in Java

查看:81
本文介绍了在Java中泛型的扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人能告诉我第一和第二代码之间的区别是什么?
MaxPQ代表优先级队列,它是可以相互比较的Key对象的集合。代码1:

  public class MaxPQ< Key extends Comparable< / p>密码>>> {
...
}

/ p>

  public class MaxPQ< Key implements Comparable< Key>> {
...
}

第二个代码不能编译,但它不直观,为什么我们需要扩展而不是实现使用通用的接口。

解决方案

区别非常简单:第二个代码片段不会编译,永远不会。对于泛型,您总是对类和接口都使用 extends 。此外,还可以使用 super 关键字,但它具有不同的语义。


Can someone tell me what the differences between the first and second codes are? MaxPQ stands for priority queue, which is a collection of "Key" objects that can be compared with each other.

Code 1:

public class MaxPQ<Key extends Comparable<Key>>{
...
}

Code 2:

public class MaxPQ<Key implements Comparable<Key>>{
...
}

The second code doesn't compile, but it is not intuitive to me why we need to extend instead of implement interfaces when using a generic.

解决方案

The difference is pretty straightforward: second code snippet does not compile and never will. With generics you always use extends, for both classes and interfaces. Also super keyword can be used there, but it has different semantics.

这篇关于在Java中泛型的扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆