javagenericsbounded-types

Bounded type parameters


Sorry guys, this might be a naive question.

I am a little bit confused by bounded type parameter and wildcard. What's the difference between <T extends String> and <? extends String>?

Thanks


Solution

  • I think you are mixing up some things here.

    <T extends String> is used when you declare a generic class.

    <? extends String> is used on instances from classes that are already generic.

    Let’s take the interface “List” from the collections framework for example: List <E> is the same like List <E extends Object> meaning that you can use the list with every datatype that inherits from Object.

    The wildcard <?> can only be used on Classes that are already generic. Taking the example from above with List<E>.Let’s say you have a method that is using the List, but you don’t want to allow every datatype that inherits from Object.

    You could use a distinct datatype like:

    public void myMethod(List<String> list){
    //…
    }
    

    But you could also use a range of datatypes that you want to allow:

    public void myMethod(List<? extends String> list{
    //..
    }
    

    In the second example you could use every datatype that is covariant with string i.e. is a child of string.

    Tldr:

    Bounds <T extends String> are used to declare the range of datatypes a generic class is supporting.

    Wildcards <? extends String> are used on classes that are already generic and restrict/limit the given datatypes to a certain range.