2.4 Accepting Parameterized Types as Arguments
So far, all of this parameterization has
occurred in the same code block.
However, that's unrealistic, and you'll quickly want to write methods that
take advantage of parameterized types. This is where generics start to
really become powerful. First, you need to understand how a method can
tell the compiler that it only accepts a specific parameterization of a
generic type.
2.4.1 How do I do that?
Just use the same syntax you've been using (and which should be getting
oddly comfortable by this point) in your argument list:
private void printListOfStrings(List<String> list, PrintStream out)This allows your method body to act on that parameterization, avoiding
throws IOException {
for (Iterator<String> i = list.iterator( ); i.hasNext( ); ) {
out.println(i.next( ));
}
}
class casts and the like. In this example, it's possible to parameterize the
Iterator as well, because the compiler ensures that only List<String>
is passed into the method. Any other List types are refused (at compiletime).
2.4.2 What about...
...trying to pass in a plain old List, without any parameterization, even if
it has only Strings in it? This actually will work, with the caveat that
you're left to your own devices in ensuring that the List has in it what
it's supposed to. If not, you'll get more ClassCastExceptions than you
can shake a stick at, all at runtime. In either case, you'll get lint warnings,
which are described in "Checking for Lint," later in this chapter.