Get and Put pattern for for wildcards Part IV

This article focus on when and where to use ( !use ) wildcards.
You need to know wildcard extends and super before reading this article
It is good practice to use wildcards where you can in a signature, since this permits the widest range of calls. But how do we decide which wildcards to use?
When and where should we use the extends and super wildcard?
– Where is it inappropriate to use a wildcard at all?
Fortunately, there’s a simple principle that helps us make decision easily. It’s the Get and Put Principle.

This principle states that:
Use an extends wildcard when you only get values out of a structure.
Use a super wildcard when you only put values into a structure.
And don’t use a wildcard when you both get and put.

And there are two exceptions:
You cannot put anything into a type declared with an extends wildcard except for the value null, which belongs to every reference type.
You cannot get anything out from a type declared with a super wildcard except for a value of type Object, which is a super type of every reference type.
The examples above (sum() and append() methods) already illustrated the first and two points of the Get and Put principle. For the last point, here’s an example:

public static double sumNumbers(Collection<Number> numbers, int n) {
 append(numbers, n);
 return sum(numbers);
}
This method calculates sum of a given N number of numbers. As the sum() method gets values out of the collection, and the append() method puts values into the collection, the sumNumbers() method should declare its first parameter as a collection of type Number, which satisfies both of constraints specified by the sum() and append() method.
The following code is a sample call:

Collection<Number> numbers = new ArrayList<>();
double sumOfTen = sumAppend(numbers, 10);

System.out.println(“Sum = ” + sumOfTen);
And the output is:
1
Sum = 55.0

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

Up ↑

%d bloggers like this: