Generics of Java 1.5 Tiger - Returning Parameterized Types
(Page 5 of 10 )
In addition to accepting parameterized types as arguments, methods in Tiger can return types that are parameterized.
How do I do that?
Remember the getListOfStrings() method, referred to in “Using Type-Safe Lists”? Here is the actual code for that method:
private List getListOfStrings() {
List list = new LinkedList ();
list.add("Hello");
list.add("World");
list.add("How");
list.add("Are");
list.add("You?");
return list;
}
While this is a workable method, it’s going to generate all sorts of lint warnings (see “Checking for Lint” for details) because it doesn’t specify a type for the List. Even more importantly, code that uses this method can’t assume that it is really getting a List of Strings. To correct this, just parameterize the return type, as well as the List that is eventually returned by the method:
private List<String> getListOfStrings() {
List<String> list = new LinkedList<String>();
list.add("Hello");
list.add("World");
list.add("How");
list.add("Are");
list.add("You?");
return list;
}
Pretty straightforward, isn’t it? The return value of this method can now be used immediately in type-safe ways:
List<String> strings = getListOfStrings();
for (String s : strings) {
out.println(s);
}
This isn’t possible, without compile-time warnings, unless getListOfStrings() has a parameterized return value.
Using Parameterized Types as Type Parameters
Collections in Tiger are generic types, and accept type parameters. However, these collections can store collections themselves, which are in turn also generics. This means that a parameterized type can be used as the type parameter to another generic type.
How do I do that?
The Map interface takes two type parameters: one for the key, and one for the value itself. While the key is usually a String or numeric ID, the value can be anything—including a generic type, like a List of Strings.
So List<String> becomes a parameterized type, which can be supplied to the Map declaration:
Map<String, List<String>> map = new HashMap<String, List<String>>();
If that’s not enough angle brackets for you, here’s yet another layer of generics to add into the mix:
Map<String, List<List<int[]>>> map = getWeirdMap();
Of course, where things get really nuts is actually accessing objects from this collection:
int value = map.get(someKey).get(0).get(0)[0];
What’s cool about this is that all the casting is handled for you—you don’t need to do any casting to List, but instead can just let the compiler unravel all your parameterized types for you.
Next: Checking for Lint >>
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.
|
|