1

What's difference between these?

public <T extends MyClass> void myMethod (ArrayList<T> list) {
}

public void myMethod (ArrayList<? extends MyClass> list) {
}
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Vitalii Vitrenko
  • 9,763
  • 4
  • 43
  • 62
  • 1
    Possible duplicate of http://stackoverflow.com/questions/16707340/when-to-use-wildcards-in-java-generics – drrob Aug 19 '15 at 09:44
  • 1
    See also https://docs.oracle.com/javase/tutorial/extra/generics/wildcards.html – drrob Aug 19 '15 at 09:48

2 Answers2

3
  1. <T extends MyClass>

    • Denotes a specific sub-type of MyClass, called T.
    • You can actually refer to the type T within the method implementation. For example, you can assign elements from the list to new variables of type T.
    • You can both add and remove elements from the list.
  2. <? extends MyClass>

    • Denotes a whole family of sub-types of MyClass. The exact substitute is unknown at compile-time and thus, cannot be referred, nor new variables of this very type can be introduced.
    • You cannot add new elements to the list (because the actual type is unknown)
    • You can only get elements from the list. They, however, can be only assigned to variables of type MyClass. Additional down-casting may be needed for some specific sub-types of MyClass.
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

In the first case, you can refer to T as being the type of the MyClass or sub-class.

In the second case T can be what ever you have defined outside this method (or nothing if you don't have a type called T)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130