A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. It is your responsibility, however, to keep track of what types of objects your collections contain. As an example, consider adding an If the compiler could keep track of the element type, you do not need to keep track of what collections you have and the need for casting would be eliminated. 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
The motivation for adding generics to the Java programming language stems from the lack of information about a collection's element type, the need for developers to keep track of what type of elements collections contain, and the need for casts all over the place. Using generics, a collection is no longer treated as a list of As an example, consider the following segment of code that creates a linked list and adds an element to the list:
As you can see, when an element is extracted from the list it must be cast. The casting is safe as it will be checked at runtime, but if you cast to a type that is different from, and not a supertype of, the extracted type then a runtime exception, Using generic types, the previous segment of code can be written as follows:
Here we say that
As you can see, you no longer need to cast to an Integer since the To reduce the clutter, the above example can be rewritten as follows...using autoboxing:
As a complete example, consider the following class, Ex1.java
Again, an explicit cast is required in the
Using Generics
Using generics, the Ex2.java
Now, if you try to compile this code, a compile-time error will be produced informing you that you cannot add an
You may have already noticed the new syntax used to create an instance of
Here Implementing Generic Types
In addition to using generic types, you can implement your own. A generic type has one or more type parameters. Here is an example with only one type parameter called
Here,
In some of your code you may need to invoke methods of the element type, such as
The important thing to note is that you are required to replace the type variables 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:
Using generics, this can be re-written as follows. Note that the
This example uses a feature of generics known as wildcards. Wildcards
There are three types of wildcards:
As an example of using wildcards, consider a
It is worth noting that the
Here is another example of a generics method that uses wildcards to sort a list into ascending order. Basically, all elements in the list must implement the
Changes to the Java Specification, JVM, and APIs
In order to support generic types, some modifications are necessary to the Java programming language, the Java virtual machine1, and the Java APIs. The notable changes to the Java APIs are related to the Collection hierarchy in the 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, 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 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
Acknowledgments
Thanks to Gilad Bracha for commenting on earlier drafts, and for providing some of the examples used in this article. 1 As used on this web site, the terms "Java virtual machine" or "JVM" mean a virtual machine for the Java platform. | ||||||||||||||||||||||||||
Oracle is reviewing the Sun product roadmap and will provide guidance to customers in accordance with Oracle's standard product communication policies. Any resulting features and timing of release of such features as determined by Oracle's review of roadmaps, are at the sole discretion of Oracle. All product roadmap information, whether communicated by Sun Microsystems or by Oracle, does not represent a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. It is intended for information purposes only, and may not be incorporated into any contract.
|
| ||||||||||||