Java Generator Extension

I looked at diff and saw this code:

public interface Vector<T extends Vector>

which has been replaced by this code:

public interface Vector<T extends Vector<T>>

I have problems with enveloping my head, what's the difference? How do they work differently?

+4
source share
1 answer

The difference between the two declarations is that the first generates a warning about the compiler, and the second does not. This is because generic types should always be used with parameters.

This declaration ensures that if X implements a vector, it must be a vector X:

class X implements Vector<X> {
...

Anything else will result in a compiler error.

In fact, this design is used in the JDK:

public abstract class Enum<E extends Enum<E>> implements Comparable<E>, Serializable {
...

this means that when we declare an listing of X, it (implicitly) extends Enum<X>

-1
source

All Articles