![]() | <!-- MAIN CONTENT --><!-- ============ --><!-- BEGIN VCD4 PFV -->
In J2SE 1.4.x you can have a collection of objects where the elements may have any reference type. Some additional work, however, is still your responsibility in the sense that you are required to keep track of what types of objects your collections contain. Also, you cannot have collections of primitive data types such as 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. <!-- <span class="sp10"> </span><br /> -->
The Need for Generics
The motivation for adding generics to the Java programming language stems from the fact that a collection doesn't contain information about the element type, the need 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: <!-- BEGIN VCD7 CODE SAMPLE COMPONENT -->
<!-- END VCD7 CODE SAMPLE COMPONENT --> 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: <!-- BEGIN VCD7 CODE SAMPLE COMPONENT -->
<!-- END VCD7 CODE SAMPLE COMPONENT --> 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: <!-- BEGIN VCD7 CODE SAMPLE COMPONENT -->
<!-- END VCD7 CODE SAMPLE COMPONENT --> As a complete example, consider the following class, Ex1.java <!-- BEGIN VCD7 CODE SAMPLE COMPONENT -->
<!-- END VCD7 CODE SAMPLE COMPONENT --> Again, an explicit cast is required in the
<!-- END VCD7 CODE SAMPLE COMPONENT -->
Using Generics
Using generics, the Ex2.java <!-- BEGIN VCD7 CODE SAMPLE COMPONENT -->
<!-- END VCD7 CODE SAMPLE COMPONENT --> 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
<!-- END VCD7 CODE SAMPLE COMPONENT --> 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
<!-- END VCD7 CODE SAMPLE COMPONENT --> Here, In some of your code you may need to invoke methods of the element type, such as
<!-- END VCD7 CODE SAMPLE COMPONENT --> 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: <!-- BEGIN VCD7 CODE SAMPLE COMPONENT -->
<!-- END VCD7 CODE SAMPLE COMPONENT --> Using generics, this can be re-written as follows. Note that the
<!-- END VCD7 CODE SAMPLE COMPONENT --> This example uses a feature of generics known as wildcards. <!-- <span class="sp10"> </span><br /> -->
Wildcards
There are three types of wildcards:
As an example of using wildcards, consider a
<!-- END VCD7 CODE SAMPLE COMPONENT --> It is worth noting that the
<!-- END VCD7 CODE SAMPLE COMPONENT --> 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
<!-- END VCD7 CODE SAMPLE COMPONENT -->
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. <!-- END RATE AND REVIEW --><!-- =================== --><!-- END OF MAIN CONTENT --> | ![]() |
![]() |
![]() |
