Saturday, 26 July 2014

Generics WildCard Pnemonics(Wildcards extends and super)

When using generics wildcards in a code it becoes difficult to reeber when to use the keywords super and extend. So jus reber PECS[Producer extends Consumer super] Whenever a collection with generics would be used as producer or as a source of data collection, use the keyword extends and whenever a collection with generics would be used as a consumer or soething in whcih you are going to insert soething use the keywords super.

for eg; consider the below 2 functions of Stack holding eleents of the type: E
void pushAll(Collection <? extends E> source);
void popAll(Collection <? super E> source);


So in case of pushAll you can call it as pushAll(Collection<Number>) or pushAll(Collection<Long>) to push into a stack holding Number as Long extends Number. which is a producer or is a source of data that you would be using it.

And pop all the objects into a collection of Objects or Number like popAll(Collection<Object>) or popAll(Collection<Number> , which is a consumer ie you are putting something to it.