O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.7. Parameterized Methods

You can define a method with its own independent set of one or more type parameters, in which case you have a parameterized method, which is also referred to as a generic method. You can have parameterized methods in an ordinary class. Methods within a generic type definition can also have independent parameters.

You could modify the listAll() method that you defined in the TryWildcardArray class in the previous example so that it is a parameterized method. Here's how that would look:

public static <T> void listAll(LinkedList<T> list) {
    for(T obj : list) {
      System.out.println(obj);
    }
  }

The <T> following the public and static keywords is the type parameter list for the generic method. Here you have only one type parameter, T, but you could have more. The type parameter list for a generic method always appears between angled brackets and should follow any modifiers such as public and static, as you have here, and should precede the return type.

Not that calling this version of the listAll() method does not require the type argument to be supplied explicitly. The type argument will be deduced from the parameter type supplied when the method is called. If you replace the listAll() code in the previous example by the version here, you should find that it works just as well. No other changes to the program are necessary to make use of it.

You could also gain some advantage by using parameterized methods in the BinaryTree<> type definition. With the present ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required