Home > Articles > Programming > Java

  • Print
  • + Share This
Like this article? We recommend

Generic Methods

A generic method is a static method or a non-static method with a type-generalized implementation. A formal type parameter section (surrounded by angle brackets) precedes the method’s return type; its syntax and meaning is identical to the generic type’s formal type parameter section. The overall syntax for a generic method is as follows:

< formal-type-parameter-section > return-type method-name ( parameter-list )
{
}

The Collections API contains many examples of generic methods. For example, java.util.Collections specifies a public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) method that replaces a specific value in a List with another value. Another example is the copyCollection() method that is presented in Listing 4.

Listing 4 GenericMethod.java

// GenericMethod.java

import java.util.*;

public class GenericMethod
{
  public static void main (String [] args)
  {
   List <String> list = new ArrayList<String> ();
   list.add ("ABC");
   list.add ("DEF");
   list.add ("ABC");

   outputCollection ("List", list);
 
   Set<String> set = new TreeSet<String> ();
   copyCollection (list, set);

   outputCollection ("Set", set);
  }

  static <T> void copyCollection (Collection<T> c1, Collection<T> c2)
  {
   for (T o: c1)
      c2.add (o);
  }

  static void outputCollection (String header, Collection<?> c)
  {
   System.out.println (header);
   System.out.println ();

   for (Object o: c)
      System.out.println (o);

   System.out.println ();
  }
}

Listing 4’s copyCollection() method solves the problem of how to add elements to a collection. Instead of employing wildcards and casting to Object, it employs a type variable (T). Because both collections use the same type variable, it is safe to add one collection’s elements to another collection.

If you recall Listing 3’s getField() and setField() methods, you might be wondering how they compare with Listing 4’s copyCollection() method. After all, these three methods employ type variables. Unlike Listing 3’s methods, however, copyCollection() is not declared within a generic type. This is true for static utility methods like those methods in the Collections class.

Also, copyCollection() has a formal type parameter section. Although the compiler infers the type for this method’s single type variable during the method’s invocation, you could explicitly specify the actual type argument if desired. This would lead to GenericMethod.<String>copyCollection (list, set);.

  • + Share This
  • 🔖 Save To Your Account