2.5 Returning Parameterized Types
In addition to accepting
parameterized types as arguments, methods in
Tiger can return types that are parameterized.
2.5.1 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( ) {While this is a workable method, it's going to generate all sorts of lint
List list = new LinkedList ( );
list.add("Hello");
list.add("World");
list.add("How");
list.add("Are");
list.add("You?");
return list;
}
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( ) {Pretty straightforward, isn't it? The return value of this method can now
List<String> list = new LinkedList<String>();
list.add("Hello");
list.add("World");
list.add("How");
list.add("Are");
list.add("You?");
return list;
}
be used immediately in type-safe ways:
List<String> strings = getListOfStrings( );This isn't possible, without compile-time warnings, unless
for (String s : strings) {
out.println(s);
}
getListOfStrings( ) has a parameterized return value.