上周看了一下java的范型,只有一个感觉,那就是真是个空壳子,太多的限制了。
特别是 类型擦除,直接字节码里把所有的类型都变成了object,简直无语.
这就是所谓的类型擦除:
引用
You cannot instantiate a type represented only as a type parameter, nor can you create an array of such a type. So for a type variable T you can't do newT() or newT[n] .
You cannot create an array whose element type is a parameterized type, with the exception of a parameterized type for which all the type arguments are unbounded wildcards. For example, "newList<String>[1] " is invalid, whereas "newList<?>[1] " is okay.
You cannot use instanceof to see if an object is an instance of a parameterized type, again with the exception of a parameterized type whose type arguments are all unbounded wildcards. The instanceof test is a runtime test, and at runtime the parameterized type has been replaced by its erasure. Since this is unlikely to perform the test you expected, the compiler rejects it. You can replace the parameterized type by its erasure if that is what you really wanted to test.
Casts involving type parameters or parameterized types are replaced with casts to the erasure of that type (see discussion below).
A catch clause cannot declare that it catches an exception represented by a type variableeven if the bound on that type variable is an exception type. The exact type of the exception must be known at compile time. (You can throw an exception so referenced, however, and you can declare the type variable in a method's throw clause.)
A generic class is not allowed to directly or indirectly extend Throwable. Given that you can't catch generic exceptions there is little point in being able to declare them.
You cannot use a parameterized type in a class literal expression (such as SingleLinkQueue<String>.class). This reinforces that there is but one class object.
比如这样的代码都是错的
public class DecimalString implements Comparable<Number>, Comparable<String>
使用范型大家可以记住这条规则就好了 。
引用
The Get and Put Principle: use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you both get and put.
希望以后的java版本使范型类能根据不同的类型生产不同的版本.
大家还可以看看 布老大的这篇文章,也能加深下理解。
http://www.iteye.com/topic/22020