Difference between these two wildcards

The following method declarations are,

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

      

and

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

      

same?

+3


source to share


2 answers


The difference is that the former does not compile, but the latter does. Is this what you asked?

If you meant the difference between:

public void testMethod (ArrayList <? extends Animal> list)

      

and

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

      

then the difference is that in the first case you cannot refer to the actual type of the elements ArrayList

, while in the second case you can.



The difference is probably more obvious if we consider the following two cases:

public void testMethod (
    ArrayList <? extends Animal> l1, 
    ArrayList <? extends Animal> l2)

      

and

public <T extends Animal> void testMethod (
    ArrayList <T> l1, ArrayList <T> l2)

      

In the first case, the first argument is ArrayList

some type that expands Animal

, the second argument is ArrayList

or some (possibly another) type that expands Animal

.

In the second case, both arguments are of ArralList

the same type that extends Animal

.

+3


source


They are not equally important in one way. In the first case, the shared parameter will be associated with the scope of the class and will not change across multiple method calls.

In the second case, the general parameter will depend on the arguments with which the method is called, and may be different for each individual call.

So, given this class:

public class MyClass<T extends Animal> {
    public void handleList1(List<T> list) {
       // implementation
    }

    public <U extends Animal> void handleList2(List<U> list) {
        // implementation
    }
}

      

Initiates it as:



MyClass<Bear> test = new MyClass<Bear>();

      

You can handleList1

only call type lists Bear

. Alternatively, you can call handleList2

like:

test.handleList2(new ArrayList<Tiger>);
test.handleList2(new ArrayList<Lion>);
test.handleList2(new ArrayList<Puma>);

      

Since the general parameter for it is determined by the argument provided by the method too.

+4


source







All Articles