Ernusc
Ernusc

Reputation: 526

What is the difference between generics

Ok, i read this question in this web-site and it did not answer me the main point.

Assume we have like this:

public <T extends Number> void someMethod(List<T> list)

AND

public void someMethod(List<? extends Number> list)

Consider that I do not need any lower bound or upper list bound. So rejection of these things, what is the difference between it in this situation? Because ? is List of unknown and T is List of T, but from one side they are similar in this situation (methods above).

(P.s. I know differences between it, but in this situation it looks for me very similar and as I consider it does not matter what to use.)

Upvotes: 1

Views: 86

Answers (2)

Ozan Tabak
Ozan Tabak

Reputation: 672

List <? extends Number> means anything that extends Number here. So assume you have classes like

public class  Example<T extends Number> {

public <T extends Number> void someMethod(List<T> list) ...

public <T extends Number> void someOtherMethod(List<T> list) ...

}

public class SomeClass extends Number {
}

public class SomeClass2 extends Number {
}

and you created an instance like

Example<SomeClass> myExample =  new Example<SomeClass>();

so when you want to use your methods here, the input parameters must be insances exactly of the same class SomeClass, we cant use SomeClass2 here. For example the following is invalid:

List<SomeClass2> someClass2 =  new ArrayList<SomeClass2>();
example.someMethod(someClass2);

but if you use <? extends Number> as an input parameter to the someMethod then it is possible. You can pass anything that extends Number, someClass2 or 3 , 4 or any other class.

Upvotes: 1

Martijn Courteaux
Martijn Courteaux

Reputation: 68847

Here:

public <T extends Number> void someMethod(List<T> list)

You can make use of the unknown type T, in your code. Eg:

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

This is not possible here:

public void someMethod(List<? extends Number> list)

Upvotes: 7

Related Questions