4
    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."

Community
  • 1
  • 1
hidemyname
  • 3,791
  • 7
  • 27
  • 41

2 Answers2

5

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).

nneonneo
  • 171,345
  • 36
  • 312
  • 383
5
public void takeThing(ArrayList<? extends Animal> list)

means "do something with a list of any subclass of Animal".

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

means "do something with a list of some particular subclass (A.K.A. T) of Animal".

If I call list.get() on the first method, all I know about the returned type is that it extends Animal. On the second method, if I had another instance of List<T>, I know that whatever type T is, both lists would accept the same type.

To take it even further, if I say

Animal animal = list.get(0);

I can no longer say

list.add(animal);

even on the very same list, because we don't have a reference to the generic subtype. If however, I declare a List<T> where <T extends Animal>, I can now say

T animal = list.get(0);
list.add(animal);

because we know that list expects elements of type T.

shmosel
  • 49,289
  • 6
  • 73
  • 138