2

I would like to understand what this Java declaration is doing:

public static <AnyType extends Comparable<? super AnyType>> int mymethod( AnyType x ) {
    /* ... */
}

From my basic knowledage of Java, I think all it's doing is telling you that the param x must be of any type, but that type must extend Comparable?

M A
  • 71,713
  • 13
  • 134
  • 174
Jdoe
  • 41
  • 5

3 Answers3

3

Your understanding is correct. This method indicates that it takes an argument of a type that extends a Comparable (Note that I would have called the type parameter T instead of AnyType for readability).

Now for the super in Comparable<? super AnyType>>, it means that this comparable implementation can actually be, for example, an implementation of Comparable<Object>, that is a comparable type that can be compared to an object. More generally, the type accepted by the method can be a Comparable which can be compared to some type that is a superclass or superinterface of it, hence the keyword super. In other words, the method can be invoked as follows:

// An object of this type can be compared to an Object
class X implements Comparable<Object> {

    @Override
    public int compareTo(Object o) {
        ...
    }


}

X x = new X();
mymethod(x);
M A
  • 71,713
  • 13
  • 134
  • 174
0

This is a generic method, i.e. its type parametrization is not related to the class' parametrization if any.

The <AnyType extends Comparable<? super AnyType>> part is the generic parametrization of the method.

The extends keyword should not be confused with the extends keyword when declaring a class: in this case it looks more like "is assignable from", in other words, IS-A.

Comparable<T> is an interface - see docs here.

Your method parametrization will make it so that your method accepts any parameter, as long as its type implements Comparable.

Specifically, it needs to be a Comparable of itself or any super-type (that's what the super part means, as opposed to extends).

For instance, you can pass a String argument because String implements Comparable<String> (amongst others).

Mena
  • 47,782
  • 11
  • 87
  • 106
0

Yes, parameter must be a sub-type of Comparable.

optimistic_creeper
  • 2,739
  • 3
  • 23
  • 37