Generics 101: Mastering the Fundamentals
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.
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 1BeforeGenerics.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 ajava.util.List-referencedjava.util.ArrayListofDoubleobjects. Somewhere in this source code lurks a bug that leads to aClassCastException. If you compileBeforeGenerics.javapre-J2SE 5.0编译器,没有错误/警告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, theClassCastExceptionresults froml.add ("Average");andsum += ((Double) iter.next ()).doubleValue ();. This exception is thrown wheniter.next()returns the previously addedStringand the cast fromStringtoDoubleis attempted.
This exception indicates that the program is nottype safe; it arises from assuming that collections arehomogeneous—they store objects of a specific type or of a family of related types. In reality, these collections areheterogeneous—they are capable of storing any type of object because the element type of collections isObject.
AlthoughClassCastExceptions 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 2AfterGenerics.java
/ / AfterGenerics.java import java.util.*; public class AfterGenerics { public static void main (String [] args) { Listl = new ArrayList (); 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 l) { double sum = 0.0; Iterator 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
It is necessary to specify
Along with four instances of
Because the compiler uses the extra type information provided by
AfterGenerics.java:18: cannot find symbol symbol : method add(java.lang.String) location: interface java.util.Listl.add ("Average"); ^ 1 error
The