bjackfly
bjackfly

Reputation: 3336

Why does T extends Comparable <? super T> include T? Meaning includes Comparable<T>?

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

Why is T extends Comparable <? super T> including T, meaning including Comparable<T> and not just the super class hierarchy? I am confused on the super keyword as I thought super would only include super class items. I am new to java and in the Java book it had the following example:

This is regarding a method in a class that was trying to limit the upper and lower bound of the hierarchy using the Java.awt.Component so the class had extends Container

class CustomComponent<T extends Container>

in the class they have the following method

void describeComponent<CustomComponent<? super JPasswordField> ref)

and then goes on to say

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

Upvotes: 3

Views: 8026

Answers (2)

Tony Coco
Tony Coco

Reputation: 41

I believe the semantic meaning of "<T extends Comparable<? super T> >" is that either T or a superclass of T must implement Comparable

Upvotes: 4

wchargin
wchargin

Reputation: 16047

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.

Upvotes: 8

Related Questions