Article Using and Programming Generics in J2SE 5.0
s, s, s, etc. But since every data type has a corresponding reference type (for example, has ), you can convert an to an before storing it in the collection. However, when an element is extracted from the collection an is returned that must be cast to an in order to ensure type safety. All this makes Java programs unnecessarily hard to read and maintain, and are more likely to fail with runtime errors. If a collection contains information about the element type, there would be no need to keep track of what collections you have and also there would be no need for casting. This would make programs easier to read and maintain, and less likely to fail at runtime. J2SE 5.0 has added a new core language feature known as generics (also known as parameterized types), that provides compile-time type safety for collections and eliminate the drudgery of casting. The effort of adding generics to Java is led by Sun Microsystems as JSR 14 under the Java Community Process (JCP). Generics are one of the most frequently requested language extensions to Java, and they have been finally added in J2SE 5.0. This article provides an introduction to programming with generics. The Need for Generics references, but you would be able to differentiate between a collection of references to s and collection of references to s. A collection with a generic type has a type parameter that specifies the element type to be stored in the collection. As an example, consider the following segment of code that creates a linked list and adds an element to the list:
will be thrown. Using generic types, the previous segment of code can be written as follows:
is a generic class that takes a type parameter, in this case. As you can see, you no longer need to cast to an Integer since the method would return a reference to an object of a specific type ( in this case). If you were to assign an extracted element to a different type, the error would be at compile-time instead of run-time. This early static checking increases the type safety of the Java language. To reduce the clutter, the above example can be rewritten as follows...using autoboxing:
, which creates a collection of two s and one , and then prints out the collection: Ex1.java
method. This class compiles fine, but throws a at runtime as it attempts to cast an to a :
class above can be written as follows: Ex2.java
to a collection of s. Therefore, generics enable more compile-time type checking and therefore mismatch errors are caught at compile-time rather than at run-time. You may have already noticed the new syntax used to create an instance of ( ). is now a parameterized type. A parameterized type consists of a class or interface name and a parameter section , which must match the number of declared parameters of , and each actual parameter must be a subtype of the formal parameter's bound types. The following segment of code shows parts of the new class definition for :
is a type variable, which is an unqualified identifier. It simply acts as a placeholder for a type to be defined when the list is used. Implementing Generic Types . A parameterized type must be a reference type, and therefore primitive types are not allowed to be parameterized types.
represents the type of elements contained in the collection. Think of as a placeholder that will be replaced by a concrete type. For example, if you write then will be replaced by . In some of your code you may need to invoke methods of the element type, such as 's and . Here is an example that takes two type parameters:
and by concrete types that are subtypes of . Generic Methods Genericity is not limited to classes and interfaces, you can define generic methods. Static methods, nonstatic methods, and constructors can all be parameterized in almost the same way as for classes and interfaces, but the syntax is a bit different. Generic methods are also invoked in the same way as non-generic methods. Before we see an example of a generics method, consider the following segment of code that prints out all the elements in a collection:
is the collection of an unknown type.
method that should be capable of drawing any shape such as circle, rectangle, and triangle. The implementation may look something like this. Here is an abstract class with three subclasses: , , and .
method can only be called on lists of and cannot be called on a list of , , and for example. In order to have the method accept any kind of shape, it should be written as follows:
interface.
package, changes to the class, and the package so that it is possible to examine a type, method, constructor or field declaration and obtain generic type information. If you like to learn about the exact changes, please see JSR 14: Adding Generics to the Java Programming Language. Behind the Scenes Generics are implemented by the Java compiler as a front-end conversion called erasure, which is the process of translating or rewriting code that uses generics into non-generic code (that is, maps the new syntax to the current JVM specification). In other words, this conversion erases all generic type information; all information between angle brackets is erased. For example, LinkedList<Integer> will become LinkedList. Uses of other type variables are replaced by the upper bound of the type variable (for example, ), and when the resulting code is not type correct, a cast to the appropriate type is inserted. Java Generics vs. C++ Templates While generics look like the C++ templates, it is important to note that they are not the same. Generics simply provide compile-time type safety and eliminate the need for casts. The main difference is encapsulation: errors are flagged where they occur and not later at some use site, and source code is not exposed to clients. Generics use a technique known as as described above, and the compiler keeps track of the generics internally, and all instances use the same class file at compile/run time. A C++ template on the other hand is just a fancy macro processor; whenever a template class is instantiated with a new class, the entire code for the class is reproduced and recompiled for the new class. Conclusion Generics are a new core feature in J2SE 5.0, and a major addition to the core language. This feature provides a useful abstract and compile-time type safety for collections and eliminates the drudgery of casting. This article provided an overview and introduction to Java generics, and showed how to use generics as well as write your own. The examples provided in this article demonstrate how useful this new core feature is. For More Information- Download J2SE 5.0 - GJ: Extending the Java programming language with type parameters - JSR 14: Adding Generics to the Java Programming Language - Generics Tutorial (Generics in the Java Programming Language) Acknowledgments Thanks to Gilad Bracha for commenting on earlier drafts, and for providing some of the examples used in this article. |
copyright © Sun Microsystems, Inc
<script language=JavaScript src="/js/omi/jsc/s_code_remote.js"></script>