站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2SE 专题Using and Programming Generics in J2SE 5.0

Using and Programming Generics in J2SE 5.0

摘要: Using and Programming Generics in J2SE 5.0
http://java.sun.com/developer/technicalArticles/J2SE/generics/


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 int to a collection; since you cannot have collections of primitive data types you must convert the int to the corresponding reference type (i.e. Integer) before storing it in the collection. Now, when the element is extracted from the collection an Object is returned that must be cast to an Integer 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 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.