10.4. Creating the Shipping Container Class¶
Follow along as we create a generic shipping container class that can hold objects of any type. Also, we point out some of the important benefits of generics.
10.4.1. Generic Types Are Invariant¶
In the previous sections, we saw how a type argument determines the types
used by a generic class. Now, let's consider how this interacts with
inheritance. Since Integer extends Number, the following assignment
is allowed:
Integer count = Integer.valueOf(17);
Number number = count;
Both variables refer to the same Integer object. Assigning the reference
value to number does not create another object or change the object's
class.
Will the following lines compile? Take a moment to make a prediction before opening the explanation.
ShippingContainer<Integer> integers = new ShippingContainer<>(17, 2.0);
ShippingContainer<Number> numbers = integers;
Explanation
The first line compiles, but the second does not. Although Integer
is a subtype of Number, ShippingContainer<Integer> is not a
subtype of ShippingContainer<Number>.
To see why this matters, suppose that the second assignment were allowed.
Both variables would refer to the same container. Through numbers,
we could then make the following method call:
numbers.setContents(Double.valueOf(3.5));
That argument is compatible with the Number parameter expected by
ShippingContainer<Number>. However, the same container would still
be accessible through integers, whose getContents() method has
return type Integer. Storing a Double reference in that container
would violate this expectation. Java rejects the assignment to
numbers at compile time, before we can create this situation.
A type relationship is covariant when a subtype relationship between
its component types carries over to the corresponding constructed types.
For example, covariance here would mean that Integer being a subtype
of Number makes ShippingContainer<Integer> a subtype of
ShippingContainer<Number>. Java does not apply that rule to generic type
arguments. Instead, they are invariant: an inheritance relationship
between two type arguments does not establish the corresponding subtype
relationship between those parameterizations of the same generic class.
This does not prevent a generic class from extending another class or implementing an interface. It means that we cannot change a container's type argument by assigning its reference to a variable with a different concrete type argument.
10.4.1.1. Accepting Different Contents¶
We can still create a container that accepts references to different kinds
of numbers. We just need to choose Number as its type argument when we
create it:
ShippingContainer<Number> numbers = new ShippingContainer<Number>(17, 2.0);
numbers.setContents(Double.valueOf(3.5));
Number contents = numbers.getContents();
Here, the constructor can accept the Integer reference produced by
boxing 17, and the setter can accept a Double reference. Both are
compatible with Number. When the getter method call completes normally,
it returns with the stored reference value, which is assigned to
contents. The container's type argument is still Number.
The distinction is between the type of the contents and the type of the
container. A ShippingContainer<Number> can store an Integer reference,
but a ShippingContainer<Integer> reference cannot be assigned to a
ShippingContainer<Number> variable.
10.4.1.2. Comparing Reference Arrays¶
Reference arrays behave differently. A subtype relationship between their
component types carries over to the array types. This is covariance, so an
Integer[] reference can be assigned to a Number[] variable:
Integer[] integers = {17};
Number[] numbers = integers;
numbers[0] = Double.valueOf(3.5);
All three lines compile. However, the last line throws an
ArrayStoreException when it executes. The two variables refer to the
same array object, whose actual component type is still Integer.
Java checks the value being stored at run time and rejects the Double
reference. Compare this with the generic container example: the incompatible
container assignment is rejected at compile time.
10.4.1.3. Accepting Containers with an Unknown Type Argument¶
What if we want to inspect the contents of either a
ShippingContainer<Integer> or a ShippingContainer<Double>? We can
use an upper-bounded wildcard:
ShippingContainer<Integer> integers = new ShippingContainer<>(17, 2.0);
ShippingContainer<? extends Number> numbers = integers;
Number contents = numbers.getContents();
The ? represents an unknown type argument. The bound extends Number
tells us that this type is Number or a subtype of Number. Therefore,
the reference value supplied by the getter is compatible with Number.
The assignment to numbers copies a reference value; both variables
still refer to the same container.
However, we cannot pass an arbitrary Integer or Double reference
to setContents through numbers. Its exact type argument is unknown.
For example, a variable of this wildcard type could refer to a
ShippingContainer<Double>, so accepting an Integer reference would
not be safe in general. Neither of these method calls compiles:
numbers.setContents(Integer.valueOf(4));
numbers.setContents(Double.valueOf(4.5));
The wildcard does not make the container immutable. We can still change
its contents through the original integers reference, and the type
system permits numbers.setContents(null). We can also call
numbers.setWeight(3.0) because that method's parameter does not depend
on the unknown type argument. These restrictions apply to the operations
available through the wildcard-typed reference.
Test Yourself
Assume that the following declarations have already executed:
ShippingContainer<Integer> integers = new ShippingContainer<>(17, 2.0);
ShippingContainer<Number> numbers = new ShippingContainer<Number>(3.5, 1.0);
ShippingContainer<? extends Number> unknown = integers;
For each statement below, decide whether it compiles. Consider each statement independently and explain your answer.
numbers = integers;
unknown = numbers;
Number value = unknown.getContents();
unknown.setContents(Integer.valueOf(8));
numbers.setContents(Integer.valueOf(8));
unknown.setContents(null);
Solution
Statement |
Compiles? |
Explanation |
|---|---|---|
|
No |
The concrete type arguments differ; |
|
Yes |
|
|
Yes |
The getter supplies a reference value compatible with |
|
No |
The unknown type argument might not accept an |
|
Yes |
The setter expects a reference value compatible with |
|
Yes |
The null reference is compatible with the unknown reference type. |
For more practice, see Question 11 in Old Quiz: Using Generics. The rules for parameterized types and reference arrays are described in JLS Section 4.10: Subtyping. Oracle's Guidelines for Wildcard Use provide additional examples of the operations available through wildcard parameterizations.
10.4.2. Additional Reading and More Examples¶
Now that you're familiar with some of the basic concepts related to generic methods in Java, you should read the following official Oracle readings:
The Java™ Tutorials: Why Use Generics?
The Java™ Tutorials: Generic Types
The Java™ Tutorials: Raw Types
If you have any questions related to the Generic Classes reading provided by Oracle, then feel free to ask them on the course Piazza.