10.8. Reading and Implementing Generic Interfaces¶
In the previous sections, we used type parameters in classes and methods. Now, let's put those ideas together. When an interface has several type parameters, start by identifying where each one is declared. Then substitute the type arguments to determine what each method expects.
The examples on this page are available in cs1302-generic-behavior. You can read the source below or compile and run the examples using the commands in the bundle's README.
Bundle
Execute the command below to download and extract the files:
bundle1302 generic-behavior
- downloading cs1302-generic-behavior bundle...
- verifying integrity of downloaded files using sha256sum...
- extracting downloaded archive...
- removing intermediate files...
subdirectory cs1302-generic-behavior successfully created
10.8.1. Bounds Describe Available Operations¶
Suppose we want to choose the greater of two items using their natural
ordering. Would a method with an unbounded type parameter T be able to
call first.compareTo(second)? No. An unbounded T gives us the
operations available through Object, which does not declare compareTo.
Here is a method with a bound that supplies the operation we need:
public static <T extends Comparable<T>> T larger(T first, T second) {
if (first.compareTo(second) >= 0) {
return first;
} // if
return second;
} // larger
In <T extends Comparable<T>>, the keyword extends introduces a bound
even though Comparable is an interface. A type argument must satisfy
Comparable<T> for that same T. For example, Integer implements
Comparable<Integer>, so we can supply two Integer references.
An arbitrary Object reference does not satisfy this requirement.
The method returns with a reference to one of its arguments. It does not create a copy of the selected object. On a tie, this implementation selects the first argument.
Sometimes the item type has no natural ordering, or we want a different
ordering. We can instead accept a Comparator<T> supplied by the caller.
That design does not require a Comparable<T> bound on T. See
Using Caller-Supplied Behavior
for a complete example of storing and invoking a comparator.
10.8.2. Relating Method and Interface Type Parameters¶
Consider this small interface. A sink is an object to which we supply values for processing:
/** Accepts values whose types are compatible with its item type.
* @param <T> the item type
*/
public interface Sink<T> {
/**
* Processes the supplied values.
* @param <S> a type compatible with the item type
* @param values the non-null iterable supplying values to process
*/
<S extends T> void acceptAll(Iterable<S> values);
} // Sink
T is declared by the interface. S is declared by acceptAll and
is available within that method's declaration. The bound S extends T
means that values of type S are compatible with T. It does not
require the two types to be different.
Here is a class that implements the interface:
/** Prints values supplied through a generic interface.
* @param <T> the item type
*/
public class Printer<T> implements Sink<T> {
/** Constructs a printer. */
public Printer() {
} // Printer
/** {@inheritDoc} */
@Override
public <S extends T> void acceptAll(Iterable<S> values) {
for (S value : values) {
T item = value;
System.out.println(item);
} // for
} // acceptAll
} // Printer
For each value supplied by the iterable, the assignment to item is
legal because of the bound. Iterable<S> lets us request an iterator
and traverse the values with an enhanced for loop. It does not promise
methods named get or size. We should not assume that every iterable
is a list, or that we can traverse it repeatedly with the same results.
Will both method calls below compile?
Sink<Number> printer = new Printer<Number>();
Iterable<Integer> values = java.util.List.<Integer>of(3, 7);
printer.<Integer>acceptAll(values);
printer.acceptAll(values);
Explanation
Yes. The interface's type argument is Number. In the first call,
we explicitly supply Integer as the method's type argument. In the
second, the compiler infers a compatible type argument from the call.
Integer satisfies the bound because it extends Number.
Neither call assigns an Iterable<Integer> reference to an
Iterable<Number> variable. The method has its own type parameter,
which lets it accept the iterable without that assignment. This is
consistent with Generic Types Are Invariant.
10.8.3. Substituting Types in an Inherited Interface¶
The UrgencyQueue API uses the same ideas in a larger declaration:
public interface Queue<T, Q extends Queue<T, Q>> { /* ... */ }
public interface UrgencyQueue<ItemType>
extends Queue<ItemType, UrgencyQueue<ItemType>> { /* ... */ }
These declarations are shown only to explain the type arguments. The project supplies the interfaces; you do not need to recreate them.
Queue has two type parameters. T describes the item type, and Q
describes a queue result type. The bound on Q requires it to be compatible
with Queue<T, Q>. UrgencyQueue supplies its own parameterized type
as the second argument. Work through the substitutions one at a time:
Declaration in |
After substitution in |
|---|---|
|
|
|
|
|
|
|
|
The name S could be replaced consistently with SubType without
changing the declaration's meaning. The API uses SubType.
The result type tells us which reference values a method may supply. It
does not require the result object to have the same runtime class as the
calling object. That requirement is stated separately in the UrgencyQueue
contracts for filter and dequeueMany(int). Read both the declaration
and the implementation requirements when deciding what a method must do.
10.8.4. Preserving the Method Contract¶
When implementing a generic interface, use @Override and preserve the
type relationships in its method declarations. In Printer, the
<S extends T> before void introduces a method type parameter. Leaving
it out does not simply shorten the declaration.
For example, will the following class correctly implement Sink<Number>?
/** Deliberately uses a non-overriding method declaration. */
public class BadOverride implements Sink<Number> {
/** Constructs this deliberately invalid example. */
public BadOverride() { }
/**
* Attempts to replace a generic method with a wildcard parameter.
* @param values the values
*/
@Override
public void acceptAll(Iterable<? extends Number> values) { }
} // BadOverride
Explanation
No. acceptAll(Iterable<? extends Number>) is not an override of
<S extends Number> void acceptAll(Iterable<S>). Although these
declarations can accept similar arguments at call sites, their method
signatures are different. They also have the same erased parameter
type, so the compiler reports a name clash.
The declaration needed here is:
@Override
public <S extends Number> void acceptAll(Iterable<S> values) {
// process the values
} // acceptAll
Replacing S with Number inside Iterable is not a correction,
either. Keep the method's own type parameter. Using raw Iterable
would discard useful type information instead of expressing the intended
contract.
10.8.5. Declaring an Array and Creating an Array¶
A generic method can declare a T[] parameter or result. That does not
mean it can create an array with new T[length]. The latter expression
is a compile-time error: a type variable does not provide the reifiable
component type required by array creation. A reifiable type has its
type information available at run time. Here, String is reifiable,
while T is not.
Compare the following declarations and expressions:
Code inside a generic method declaring |
Compiles? |
Meaning |
|---|---|---|
|
Yes |
Declares an array reference variable; creates no array. |
|
No |
Attempts to create an array with a non-reifiable component type. |
|
Yes |
Creates an array whose runtime component type is |
|
With an unchecked-cast warning |
Still creates an |
The unchecked cast is not a way to obtain a String[] when a caller
chooses String for T. A later assignment to a String[] variable
can throw ClassCastException. The array object still has component
type Object.
Instead, the caller can supply an object that knows how to create an array
of the desired type. The lambda chapter's
Supplying an Array Generator shows this approach using IntFunction<T[]>.
Allocating the array creates element variables, initially containing the
null reference. It does not create the objects that those elements might
later refer to.
10.8.6. Continue Your Practice¶
Try Questions 12–14 in Old Quiz: Using Generics. For the language rules behind these examples, see JLS Section 8.4.2: Method Signature and JLS Section 15.10.1: Array Creation Expressions. The project-specific declarations and requirements are in the Queue and UrgencyQueue API documentation.