In Java, what can a wild card do that regular generics cannot do? -


i new java. in this document give use case using wildcard:

static void printcollection(collection c) {     iterator = c.iterator();     (int k = 0; k < c.size(); k++) {         system.out.println(i.next());     } } 

this solution:

static void printcollection(collection<?> c) {     (object e : c) {         system.out.println(e);     } } 

but same without wild card:

static <t> void printcollection(collection<t> c) {     iterator = c.iterator();     (int k = 0; k < c.size(); k++) {         system.out.println(i.next());     } } 

can show me simple use case regular generics won't work wild card will?

update: answers on here when use wildcards in java generics? not tell need wildcard. in fact other way around.

one thing wildcards allow declare types agnostic towards particular type parameter, example "list of kind of list":

list<list<?>> listofanylist = ...;  listofanylist.add( new arraylist<string>() ); listofanylist.add( new arraylist<double>() ); 

this impossible without wildcard:* because element lists may have different types each other.

and if try capture it, find can't:

static <e> void m(list<list<e>> listofparticularlist) {}  m( listofanylist ); // <- won't compile 

another thing wildcards allow type parameters cannot set lower bound. (a type parameter can declared extends bound, not super bound.**)

class protector {     private string secretmessage = "abc";      void pass(consumer<? super string> consumer) {         consumer.accept( secretmessage );     } } 

suppose pass instead declared take consumer<string>. suppose had consumer<object>:

class collectorofanything implements consumer<object> {     private list<object> mycollection = new arraylist<>();      @override     public void accept(object anything) {         mycollection.add( );     } } 

the problem is: can't pass method accepting consumer<string>. declaring consumer<? super string> means can pass consumer accepts string. (also see java generics: pecs?.)

most of time, wildcards let make tidy declarations.

if don't need use type, don't have declare type parameter it.


* technically possible raw type, raw types discouraged.

** don't know why java doesn't allow super type parameter. 4.5.1. type arguments of parameterized types may hint has limitation of type inference:

unlike ordinary type variables declared in method signature, no type inference required when using wildcard. consequently, permissible declare lower bounds on wildcard […].


Comments

Popular posts from this blog

shopping cart - Page redirect not working PHP -

php - How to modify a menu to show sub-menus -

python - Installing PyDev in eclipse is failed -