Home > Articles > Programming > Java

Generics 101: Mastering the Fundamentals

  • Print
  • + Share This
Java 2 Standard Edition 5.0 introduced generics to Java developers. Since their inclusion in the Java language, generics have proven to be controversial: many language enthusiasts believe that the effort to learn generics outweighs their importance to the language. Fortunately, as Jeff Friesen discusses here, you can master the fundamentals without expending much effort.

Editor's Note: This article is several years old and has been updated. Please do yourself and your Java skills a favor and go to the newest version, Generics 101, Part 1: What Are Generics?, posted in 2011.

Like this article? We recommend

Java 2 Standard Edition 5.0 introduced generics to Java developers. Since their inclusion in the Java language, generics have proven to be controversial: many language enthusiasts believe that the effort to learn generics outweighs their importance to the language. Fortunately, as this article shows, you can master the fundamentals without expending much effort.

This article helps you master generics fundamentals by first focusing on type safety, in which you discover the motivation for adding generics to Java. The article next explores generic types and generic methods, which manifest generics at the source code level. For brevity, this article focuses on essentials and does not delve into too many details—complete coverage of generics would probably occupy an entire book.

Type Safety

Java developers strive to create Java programs that work correctly for their clients—no developer wants code to fail and then be faced with an angry client. Failure is typically indicated through thrown exceptions; ClassCastExceptions (resulting from improper casting) are among the worst because they usually are not expected (and are not logged so that their causes can be found). Take a look at Listing 1.

Listing 1 BeforeGenerics.java

// BeforeGenerics.java

import java.util.*;

public class BeforeGenerics
{
  public static void main (String [] args)
  {
   List l = new ArrayList ();

   l.add (new Double (101.0));
   l.add (new Double (89.0));
   l.add (new Double (33.0));

   double avg = calculateAverage (l);
   System.out.println ("Average = " + avg);

   l.add ("Average");
   avg = calculateAverage (l);
   System.out.println ("Average = " + avg);
  }

  static double calculateAverage (List l)
  {
   double sum = 0.0;
   Iterator iter = l.iterator ();
   while (iter.hasNext ())
     sum += ((Double) iter.next ()).doubleValue ();

   return sum / l.size ();
  }
}

Listing 1 averages the floating-point values in a java.util.List-referenced java.util.ArrayList of Double objects. Somewhere in this source code lurks a bug that leads to a ClassCastException. If you compile BeforeGenerics.java with a pre-J2SE 5.0 compiler, no error/warning message outputs. Instead, you only discover this bug when you run the program:

Average = 74.33333333333333
Exception in thread "main" java.lang.ClassCastException: java.lang.String
    at BeforeGenerics.calculateAverage(BeforeGenerics.java:28)
    at BeforeGenerics.main(BeforeGenerics.java:19)

From a technical perspective, the ClassCastException results from l.add ("Average"); and sum += ((Double) iter.next ()).doubleValue ();. This exception is thrown when iter.next() returns the previously added String and the cast from String to Double is attempted.

This exception indicates that the program is not type safe; it arises from assuming that collections are homogeneous—they store objects of a specific type or of a family of related types. In reality, these collections are heterogeneous—they are capable of storing any type of object because the element type of collections is Object.

Although ClassCastExceptions can occur from many sources, they frequently result from violating the integrity of a collection that is considered to be homogeneous. Solving collection-oriented type safety problems motivated the inclusion of generics in the Java language (and an overhaul of the Collections API to support generics). With generics, the compiler can now detect type-safety violations. Examine Listing 2.

Listing 2 AfterGenerics.java

// AfterGenerics.java

import java.util.*;

public class AfterGenerics
{
  public static void main (String [] args)
  {
   List<Double> l = new ArrayList<Double> ();

   l.add (101.0);
   l.add (89.0);
   l.add (33.0);

   double avg = calculateAverage (l);
   System.out.println ("Average = " + avg);

   l.add ("Average");
   avg = calculateAverage (l);
   System.out.println ("Average = " + avg);
  }

  static double calculateAverage (List<Double> l)
  {
   double sum = 0.0;
   Iterator<Double> iter = l.iterator ();
   while (iter.hasNext ())
     sum += iter.next ();

   return sum / l.size ();
  }
}

Although Listing 2 is similar to Listing 1, there are fundamental differences. For example, List<Double> l = new ArrayList<Double> (); replaces List l = new ArrayList ();. Specifying Double between angle brackets tells the compiler that l references a homogeneous list of Double objects—Double is the element type.

It is necessary to specify <Double> after both List and ArrayList to prevent non-Double objects from being stored in the list, in calculateAverage()’s parameter list to prevent this method from being able to store non-Doubles in the list, and after Iterator to eliminate a (Double) cast when retrieving objects from the list.

Along with four instances of <Double> that provide type information to the compiler, Listing 2 also uses autoboxing to simplify the code. For example, the compiler uses autoboxing with this type information to expand l.add (101.0); to l.add (new Double (101.0));, and to expand sum += iter.next (); to sum += ((Double) iter.next ()).doubleValue ();.

Because the compiler uses the extra type information provided by <Double> to verify that the list can only contain Doubles, the (Double) cast is no longer needed (although it can be specified). Eliminating this cast reduces source code clutter. Furthermore, this type information aids the compiler in detecting attempts to store non-Double objects in the list:

AfterGenerics.java:18: cannot find symbol
symbol : method add(java.lang.String)
location: interface java.util.List<java.lang.Double>
   l.add ("Average");
    ^
1 error

The <Double> specification is an example of generics, a set of language enhancements that promote type safety through generic types and generic methods. The following two sections explore each of these enhancement categories; they provide you with an overview of what generic types and generic methods have to offer.

  • + Share This
  • 🔖 Save To Your Account