java - Generic Wildcard Bounded Type vs Generic Bounded Type Parameter -


this question has answer here:

while on quest on understanding java generics, i've come across this:

public static <t extends number> int sumlistelems(list<t> list){    int total = 0;    for(number n: list)        total += n.intvalue();    return total; } 

suppose have following method adds elements of list, restricted lists holds number.

but what's difference of code one:

public static int sumlistelems(list<? extends number> list){    int total = 0;    for(number n: list)       total += n.intvalue();    return total; } 

both of them compiles , executes expected. differences between two? aside syntax? when prefer using wildcard on former?

well, yes, using wildcard approach, can't add new element on list except null, or won't compile. aside that?

no difference in case. more complex signatures, may need reuse defined type defining needed. like:

public static <t extends number> void foo(t bar, list<t> mylist)... 

this guarantees not both bar , elements of mylist extend number, of same type. not positively enforce other syntax.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -