generics - Why can't a Java type parameter have a lower bound? -


i gather cannot bind java generics type parameter lower bound (i.e. using super keyword). reading angelika langer generics faq had on subject. comes down lower bound being useless ("not making sense").

i'm not convinced. can imagine use them more flexible callers of library method produces typed result. imagine method created array list of user-specified size , filled empty string. simple declaration be

public static arraylist<string> createarraylistfullofemptystrings(int i); 

but that's unnecessarily restrictive clients. why can't invoke method this:

//should compile list<object> l1 = createarraylistfullofemptystrings(5);  list<charsequence> l2 = createarraylistfullofemptystrings(5); list<string> l3 = createarraylistfullofemptystrings(5);  //shouldn't compile list<integer> l4 = createarraylistfullofemptystrings(5); 

at point tempted try following definition:

public static <t super string> list<t> createarraylistfullofemptystrings(int size) {   list<t> list = new arraylist<t>(size);   for(int = 0; < size; i++) {      list.add("");   }   return list; } 

but not compile; super keyword illegal in context.

is example above bad example (ignoring below)? why isn't lower bound useful here? , if useful, what's real reason not permitted in java?

p.s.

i know better organization might this:

public static void populatelistwithemptystrings(list<? super string> list, int size);  list<charsequence> list = new arraylist<charsequence>(); populatelistwithemptystrings(list, 5); 

can purpose of question pretend due requirement, need both operations in 1 method call?

edit

@tom g (justifiably) asks benefit having list<charsequence> have on list<string>. one, nobody said returned list immutable, here's 1 advantage:

list<charsequence> l2 = createarraylistfullofemptystrings(5); l2.add(new stringbuilder("foo").append("bar")); 

basically, not useful enough.

i think example points out advantage of lower bound, feature faq calls restricted instantiation:

the bottom line is: " super " bound buy you restriction supertypes of number can used type arguments. ....

but other posts point out, usefulness of feature can limited.

due nature of polymorphism , specialization, upper bounds far more useful lower bounds described faq (access non-static members , type erasure). suspect complexity introduced lower bounds aren't worth limited value.


op: want add think did show useful, not useful enough. come irrefutable killer use cases , i'll jsr. :-)


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -