Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between wildcard and 'T'? [duplicate]

Tags:

java

    public <? extends Animal> void takeThing(ArrayList<?> list)
    public <T extends Animal> void takeThing(ArrayList<T> list)

Why this statement is wrong? I mean why the ? can't be used in the front? But T can. What is the difference?

Possible duplicate "When to use wildcards in Java Generics?"

Here is an answer for this question.But I don't get what this mean. "if you say void then there is no return type. if you specify then there is a return type. i didn't know that you can specify to have return type or no return type."

like image 624
hidemyname Avatar asked Dec 26 '22 08:12

hidemyname


1 Answers

Writing <T extends Animal> binds the type name T, so that it can be referred to later in the definition (including in the parameter list).

If you wrote <? extends Animal>, then you did not name the type. Therefore, you cannot refer to it later. You can't refer to it as ? later because that could be ambiguous (what if you had two type parameters?).

Java forbids you from writing public <?> ... because such a declaration is useless (the type parameter is not named so it cannot be used).

like image 72
nneonneo Avatar answered Dec 28 '22 06:12

nneonneo