所属类别:技术博客
文章作者:ruixj
特别推荐:免费发布信息 承包关键词~~抢爆了!HOT!
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.The Need for GenericsThe 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 Object references, but you would be able to differentiate between a collection of references to Integers and collection of references to Bytes. 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:LinkedList list = new LinkedList();list.add(new Integer(1));Integer num = (Integer) list.get(0);
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, ClassCastException will be thrown.Using generic types, the previous segment of code can be written as follows:LinkedList list = new LinkedList();list.add(new Integer(1));Integer num = list.get(0);
Here we say that LinkedList is a generic class that takes a type parameter, Integer in this case.As you can see, you no longer need to cast to an Integer since the get() method would return a reference to an object of a specific type (Integer 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:LinkedList list = new LinkedList();list.add(1);int num = list.get(0);
As a complete example, consider the following class, Ex1, which creates a collection of two Strings and one Integer, and then prints out the collection:Ex1.javaimport java.util.*;public class Ex1 {
private void testCollection() {
List list = new ArrayList();
list.add(new String("Hello world!"));
list.add(new String("Good bye!"));
list.add(new Integer(95));
printCollection(list);
}
private void printCollection(Collection c) {
Iterator i = c.iterator();
while(i.hasNext()) {
String item = (String) i.next();
System.out.println("Item: "+item);
}
}
public static void main(String argv[]) {
Ex1 e = new Ex1();
e.testCollection();
}}
Again, an explicit cast is required in the printCollection method. This class compiles fine, but throws a CLassCastException at runtime as it attempts to cast an Integer to a String:Item: Hello world!Item: Good bye!Exception in thread "main" java.lang.ClassCastException: java.lang.Integer
at Ex1.printCollection(Ex1.java:16)
at Ex1.testCollection(Ex1.java:10)
at Ex1.main(Ex1.java:23)
Using GenericsUsing generics, the Ex1 class above can be written as follows:Ex2.javaimport java.util.*;public class Ex2 {
private void testCollection() {
List list = new ArrayList();
list.add(new String("Hello world!"));
list.add(new String("Good bye!"));
list.add(new Integer(95));
printCollection(list);
}
private void printCollection(Collection c) {
Iterator i = c.iterator();
while(i.hasNext()) {
System.out.println("Item: "+i.next());
}
}
public static void main(String argv[]) {
Ex2 e = new Ex2();
e.testCollection();
}}
Now, if you try to compile this code, a compile-time error will be produced informing you that you cannot add an Integer to a collection of Strings. 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 ArrayList (List list = new ArrayList()). ArrayList is now a parameterized type. A parameterized type consists of a class or interface name E and a parameter section , which must match the number of declared parameters of E, 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 ArrayList:public class ArrayList extends AbstractList implements List,
RandomAccess, Cloneable, Serializable {
// ...}
Here E 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 TypesIn 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 E. A parameterized type must be a reference type, and therefore primitive types are not allowed to be parameterized types.interface List {
void add(E x);
Iterator iterator();}interface Iterator {
E next();
boolean hasNext();}class LinkedList implements List {
// implementation
}
Here, E represents the type of elements contained in the collection. Think of E as a placeholder that will be replaced by a concrete type. For example, if you write LinkedList then E will be replaced by String.In some of your code you may need to invoke methods of the element type, such as Object's hashCode() and equals(). Here is an example that takes two type parameters:class HashMap extends AbstractMap implements Map {
// ...
public V get(Object k) {
...
int hash = k.hashCode();
...
}
// ...
}
The important thing to note is that you are required to replace the type variables K and V by concrete types that are subtypes of Object.Generic MethodsGenericity 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:public void printCollection(Collection c) {
Iterator i = c.iterator();
for(int k = 0;k is the collection of an unknown type.void printCollection(Collection<?> c) {
for(Object o:c) {
System.out.println(o);
}}
This example uses a feature of generics known as wildcards.WildcardsThere are three types of wildcards:"? extends Type": Denotes a family of subtypes of type Type. This is the most useful wildcard"? super Type": Denotes a family of supertypes of type Type"?": Denotes the set of all types or anyAs an example of using wildcards, consider a draw() method that should be capable of drawing any shape such as circle, rectangle, and triangle. The implementation may look something like this. Here Shape is an abstract class with three subclasses: Circle, Rectangle, and Triangle.public void draw(List shape) {
for(Shape s: shape) {
s.draw(this);
}}
It is worth noting that the draw() method can only be called on lists of Shape and cannot be called on a list of Circle, Rectangle, and Triangle for example. In order to have the method accept any kind of shape, it should be written as follows:public void draw(List<? extends Shape> shape) {
// rest of the code is the same}
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 Comparable interface.public static > void sort(List list) {
Object a[] = list.toArray();
Arrays.sort(a);
ListIterator i = list.listIterator();
for(int j=0; j will become LinkedList. Uses of other type variables are replaced by the upper bound of the type variable (for example, Object), and when the resulting code is not type correct, a cast to the appropriate type is inserted.Java Generics vs. C++ TemplatesWhile 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 type erasure 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.ConclusionGenerics 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.发表于 @ 2006年09月25日 16:41:00评论(loading...AddFeedbackCountStack("1280976"))编辑新一篇:C++中的继承旧一篇:想成为嵌入式程序员应知道的0x10个基本问题
相关信息· IDesign C
· SnagIt抓图功能之特色技巧两则
· JBoss应用服务器5.0正式发布
· 分页控制
35223
65170
