3
class BinarySearch<T extends Comparable<? super T> >

为什么T extends Comparable <? super T>包括T,意味着包括Comparable<T>而不只是超类层次结构?我对 super 关键字感到困惑,因为我认为 super 只会包含超类项目。我是 Java 新手,在 Java 书中它有以下示例:

这是关于一个类中的一个方法,该方法试图使用 Java.awt.Component 限制层次结构的上限和下限,因此该类扩展了 Container

class CustomComponent<T extends Container>

在课堂上,他们有以下方法

void describeComponent<CustomComponent<? super JPasswordField> ref)

然后继续说

请注意,作为 JTextField 的超类的 JPasswordField 本身在允许的对象列表中被省略。

4

2 回答 2

7

From Lower Bounded Wildcards, a section of the Generics section of The Java Tutorial:

... a lower bounded wildcard restricts the unknown type to be a specific type or a super type of that type.

(bold mine, emphasis theirs)

Thus, the set of classes that match T extends Comparable<T> is a subset of the set of classes that match T extends Comparable<? super T>. The wildcard ? super T itself matches T and any superclasses of T.

In other words, the assumption that "super would only include super class items" is simply incorrect.

Your confusion in the example may also arise from the fact that JTextField is a superclass of JPasswordField; in other words, JPasswordField extends JTextField. The example would match any of the following classes:

  • javax.swing.JPasswordField
  • javax.swing.JTextField
  • javax.swing.JTextComponent
  • javax.swing.JComponent
  • java.awt.Container
  • java.awt.Component
  • java.lang.Object

The example would make much more sense as the following:

void describeComponent(CustomComponent<? super JTextField> ref) {...}

Note that JPasswordField, which is a subclass of JTextField, itself is omitted in the list of permissible objects, because it is not a superclass of JTextField.

于 2013-08-10T16:08:31.573 回答
3

我相信“<T extends Comparable<? super T>>”的语义是 T 或 T 的超类必须实现 Comparable

于 2013-09-07T16:27:17.970 回答