4

I was looking at a diff and saw this code:

public interface Vector<T extends Vector>

which was replaced by this code:

public interface Vector<T extends Vector<T>>

I have trouble wrapping my head around it, what is the difference? How do they work differently?

talloaktrees
  • 3,508
  • 6
  • 28
  • 43
  • 2
    I think this page should answer all of your questions: http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it – robbmj Dec 23 '13 at 02:34
  • 1
    Actually it does answer my question, I sometimes have trouble parsing the language of java generics parameterization in the wild. Knowing that it is a raw type helps me think of it in terms of ArrayList vs ArrayList, etc. – talloaktrees Dec 23 '13 at 02:37
  • Very interesting recursive generic. – Mad Physicist Dec 23 '13 at 02:38
  • This is the actual explanation: http://stackoverflow.com/questions/211143/java-enum-definition – Brian Roach Dec 23 '13 at 02:59
  • Both of them do not make much sense and whoever wrote it doesn't realize that it can be done much simpler with just `public interface Vector`. – newacct Dec 24 '13 at 03:13

1 Answers1

-1

The difference between these two declarations is that the first one produces compiler warning and the second one doesn't. This is because generic types should always be used with parameters.

This declaration ensures that if X implements Vector it must be Vector of X :

class X implements Vector<X> {
...

Anything else will produce a compiler error.

Actually such construct is used in JDK:

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

it means that when we declare enum X it (implicitly) extends Enum<X>

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
  • "This declaration ensures that if X implements Vector it must be Vector of X" No it doesn't. Now we can make `class Y implements Vector` – newacct Dec 24 '13 at 03:14
  • class Y implements Vector gives compile error – Evgeniy Dorofeev Dec 24 '13 at 06:34
  • No it doesn't, given class `X` as you've defined it above. Have you even tried it? – newacct Dec 24 '13 at 07:14
  • Bound mismatch: The type X is not a valid substitute for the bounded parameter of the type Vector – Evgeniy Dorofeev Dec 24 '13 at 07:24
  • C'mon. I don't know what problem you are having, but you are doing something wrong. This is guaranteed to compile: interface Vector> {} class X implements Vector {} class Y implements Vector {} – newacct Dec 26 '13 at 05:00