Vitalii Vitrenko
Vitalii Vitrenko

Reputation: 10395

What's difference between these generic methods?

What's difference between these?

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

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

Upvotes: 1

Views: 84

Answers (2)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62864

  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.

Upvotes: 3

Peter Lawrey
Peter Lawrey

Reputation: 533500

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)

Upvotes: 2

Related Questions