Java 1.5 Tiger A Developers Notebook [Electronic resources]

David Flanagan, Brett McLaughlin

نسخه متنی -صفحه : 131/ 29
نمايش فراداده

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( ) {
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.