Generics of Java 1.5 Tiger - Accepting Parameterized Types as Arguments
(Page 4 of 10 )
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.
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)
throws IOException {
for (Iterator<String> i = list.iterator(); i.hasNext(); ) {
out.println(i.next());
}
}
This allows your method body to act on that parameterization, avoiding 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 compile-time).
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.
Next: Returning Parameterized Types >>
More Java Articles
More By O'Reilly Media
|
This article was taken from chapter two of Java 1.5 Tiger: A Developer's Notebook, written by Brett McLaughlin and David Flanagan (O'Reilly, 2004; ISBN: 0596007388). Check it out at your favorite bookstore. Buy this book now.
|
|