Monday, December 7, 2015

What is Wildcard Capture , Get and Put Principle and wildcard restrictions?

What is Wildcard Capture ?
When a generic method is called then the type parameter is choosen to replace the unknow type represented by the wildcard.
this is called wildcapture. in short when any type replace the wildcard in the method or any collection then it is called wildcard capture.

What is Get and Put Principle ?
In generics use extends with wildcard ( ? extends AnyType) when you just want to GET values from the collection and
use super with wildcard ( ? super AnyType) whenever you want to put values in to collection.

What are the restrictions on wildcard ??

1) wildcards cannot be used with the instance creation(new)
List<?>  dataList = new ArrayList<?>(); // INVALID , it will show compile time error
Map<String, ? extends Number> dataMap = new HashMap<String, ? extends Number>(); // this will show compile time error

the reason behind this restriction is the GET and PUT principle because when you want to do both then it requires a precise type.
so it requires precise type at the instance creation.

But yes this is allowed
List<List<?>> lists = new ArrayList<List<?>>(); 
because here each individual list will have specific type related data.
here the wildcard type prohibits us from extracting elements from the inner lists as any type
other than Object.

2) Wildcard cannot be used in the explicit type parameter in generic method call
when a generic method includes a explicit type parameter then that method call cannot contain a wildcard as a type parameteer.
example
public static <T> List<T> dataList() { return new ArrayList<T>(); }

above method cannot be called as List<?> list = Lists.<?>factory();  it will give compile time error.
but it can be called as List<List<?>> = Lists.<List<?>>factory(); as explained above witt the nested list example.

and yes whatever restrictions are applied with the instance creations all that are applied with the supertype.
any superclass or superinterface has the type parameter then that cannot be wild card

class AnyList extends ArrayList<?> { } //  this will give compile-time error

class MyList implements List<?> { } // this will give  compile-time error

No comments:

Post a Comment

Scrum and Scrum master

Scrum  Scrum is a framework which helps a team to work together.  It is like a rugby team (the scrum name comes from rugby game). Scrum enco...