On the surface, both the syntax and the application environment (such as the container class) and the generic type (or generic type) are similar to the template in C ++. However, this similarity is limited to the surface. in Java, generics are basically fully implemented in the compiler. The Compiler executes the type check and type inference, and then generates common non-generic bytecode. This implementation technology is called Erasure (the compiler uses generic type information to ensure type security and then clears bytecode before it is generated). This technology is somewhat odd, and sometimes it has some confusing consequences. Although the paradigm is a major step towards type security for Java classes, it is almost certainly a headache (sometimes intolerable) when learning to use generics.
Note: This document assumes that you have a basic understanding of the model in JDK 5.0.
Generics are not covariant.
Although it is helpful to regard the set as an array abstraction, the array also has some special properties that the set does not have. Arrays in Java are covariant. That is to say, if integer is extended by number (as is true), not only integer is number, but integer [] is also number []. you can pass the number [] or assign it to integer []. (More formally, if number is an integer supertype, number [] is also an integer [] supertype ). You may think this principle applies to the generic type -- list <number> is a list <integer> supertype, you can pass list <integer> where list <number> is required. Unfortunately, this is not the case.
It is not allowed to do so for a very good reason: doing so will undermine the type security generic type to be provided. If you can grant list <integer> to list <number>. The following code allows non-integer content to be placed in the list <integer>:
1 List<Integer> li = new ArrayList<Integer>();2 List<Number> ln = li; // illegal3 ln.add(new Float(3.1415));
Because ln is list <number>, it seems completely legal to add float to it. However, if ln is the alias of Li, this destroys the type security commitment contained in the Li definition-it is an integer list, which is why generic types cannot be changed together.
Other coordination issues
Another consequence of changing arrays while changing generics is that arrays of the generic type cannot be instantiated (new list <string> [3] is invalid ), unless the type parameter is an unbound wildcard (new list <?> [3] is valid ). Let's take a look at the consequences of declaring a Generic Array:
1 List<String>[] lsa = new List<String>[10]; // illegal2 Object[] oa = lsa; // OK because List<String> is a subtype of Object3 List<Integer> li = new ArrayList<Integer>();4 li.add(new Integer(3));5 oa[0] = li;6 String s = lsa[0].get(0);
The last row will throw classcastexception, because this will fill in list <integer> in the location where it should be list <string>. Arrays are not allowed to instantiate arrays of the generic type unless the type parameter is an unbound wildcard, such as list <?> ).
Construction Delay
Because it can be erased, list <integer> and list <string> are the same class. The Compiler generates only one class (different from C ++) when compiling list <v> ). Therefore, when compiling the list <v> class, the compiler does not know the type represented by V, therefore, it cannot process the type parameter in the list <v> class definition as it knows the specific type represented by the class (V in list <v> ).
Because list <string> and list <integer> cannot be distinguished during running, the construction of variables identified by generic parameters becomes a problem. There is a lack of type information during the runtime, which makes it difficult for generic containers and generic classes that want to create protective copies.
For example, generic FOO:
1 class Foo<T> {2 public void doSomething(T param) { ... }3 }
What if the dosomething () method wants to copy the input Param parameter? There are not many options. You may want to implement dosomething () as follows ():
1 public void doSomething(T param) {2 T copy = new T(param); // illegal3 }
However, you cannot use type parameters to access constructors, because you do not know the classes to be constructed during compilation, so you do not know which constructors to use. When using generics, the constraints such as "t must have a copy constructor" (or even a constructor without parameters) cannot be expressed, therefore, you cannot use the class constructor represented by generic type parameters.
What about clone? Suppose in the definition of Foo, t extends cloneable:
1 class Foo<T extends Cloneable> {2 public void doSomething(T param) {3 T copy = (T) param.clone(); // illegal4 }5 }
Unfortunately, you still cannot call Param. Clone (). Why? Because clone () protects access in objects, calling clone () must be done by modifying clone () to public access class reference. But re-declaring clone () as public does not know T, so cloning does not help.
Create a wildcard reference
Therefore, it is not possible to copy the type reference of the class during compilation. How about the wildcard type? Assume that the type to be created is set <?> Parameter. You know that set has a copy constructor. Others may have told you that if you do not know the type of the content to be set, you 'd better use set <?> Replace the set of the original type, because this method causes fewer unchecked type conversion warnings. Therefore, you can try to write as follows:
1 class Foo {2 public void doSomething(Set<?> set) {3 Set<?> copy = new HashSet<?>(set); // illegal4 }5 }
Unfortunately, you cannot use a wildcard type parameter to call a generic constructor, even if you know that such constructor exists. However, you can do this:
1 class Foo {2 public void doSomething(Set<?> set) {3 Set<?> copy = new HashSet<Object>(set);4 }5 }
This construction is not so intuitive, but it is type-safe and can be like new hashset <?> (SET.
Construct an array
How to Implement arraylist <v>? Assume that the arraylist class manages a V array. You may want to use the arraylist <v> constructor to create a V array:
1 class ArrayList<V> {2 private V[] backingArray;3 public ArrayList() {4 backingArray = new V[DEFAULT_SIZE]; // illegal5 }6 }
However, this code cannot work-the type array represented by the type parameter cannot be instantiated. The compiler does not know what type V represents, so it cannot instantiate the V array.
The collections class bypasses this problem through a awkward method. during the compilation of the collections class, a warning that the type conversion is not checked will be generated. The arraylist constructor is as follows:
1 class ArrayList<V> {2 private V[] backingArray;3 public ArrayList() {4 backingArray = (V[]) new Object[DEFAULT_SIZE];5 }6 }
Why didn't these codes generate arraystoreexception when accessing the backingarray? In any case, the object array cannot be assigned to the string array. Because generics are implemented through erasure, The backingarray type is actually object [], because the object replaces v. This means: in fact, this class expects backingarray to be an array of objects, but the compiler needs to perform additional type checks to ensure that it contains objects of the V type. This method works very well, but it is quite awkward, so it is not worth doing the same. (For more information, see references ).
Another way is to declare the backingarray as an object array and forcibly convert it to V [] in each place where it is used. The conversion warning is still not checked for the type (the same as the previous method), but it makes some ambiguous assumptions clearer (for example, backingarray should not escape the implementation of arraylist ).
Other methods
The best way is to pass the class text (FOO. Class) to the constructor so that the implementation can know the value of T at runtime. The reason for not using this method is backward compatibility-the new generic collection class cannot be compatible with previous versions of the collections framework.
In the following code, arraylist uses the following method:
1 public class ArrayList<V> implements List<V> {2 private V[] backingArray;3 private Class<V> elementType;4 public ArrayList(Class<V> elementType) {5 this.elementType = elementType;6 backingArray = (V[]) Array.newInstance(elementType, DEFAULT_LENGTH);7 }8 }
But wait! If array. newinstance () is called, unchecked type conversion will occur. Why? This is also due to backward compatibility. The signature of array. newinstance () is:
1 public static Object newInstance(Class<?> componentType, int length)
Instead of type-safe:
1 public static<T> T[] newInstance(Class<T> componentType, int length)
Why is array generalized in this way? It is also used to maintain backward compatibility. To create an array of basic types, such as int [], you can use the type field in the appropriate Wrapper class to call array. newinstance () (for int, integer can be passed. type ). Use the class <t> parameter instead of the class <?> Generalized array. newinstance () has better type security for the reference type, but you cannot use array. newinstance () to create an instance of the basic type array. A new newinstance () version may be provided for the reference type in the future.
Here we can see a pattern-many problems or trade-offs related to Generics do not come from generics themselves, but are side effects of maintaining compatibility with existing code.
Generalized existing classes
There is not much skill in converting existing library classes to use generics, but it is the same as normal, and backward compatibility will not come out of thin air. I have discussed two examples, in which backward compatibility limits the generalization of class libraries.
Another general method may not have backward compatibility issues, which is collections. toarray (object []). The array passed in toarray () has two purposes -- if the set is small enough, you can directly put its content in the provided array. Otherwise, use reflection to create a new array of the same type to accept the results. If you rewrite the collections framework from the beginning, it is very likely that the parameter passed to collections. toarray () is not an array, but a class text:
1 interface Collection<E> {2 public T[] toArray(Class<T super E> elementClass);3 }
Because the collections framework is widely used as an example of a good class design, but its design is subject to backward compatibility constraints, it deserves your attention and should not be blindly followed.
First, an important aspect of the commonly obfuscated generic collections API is the signatures of containsall (), removeall (), and retainall. You may think that the signatures for remove () and removeall () should be:
1 interface Collection<E> {2 public boolean remove(E e); // not really3 public void removeAll(Collection<? extends E> c); // not really4 }
But it is actually:
1 interface Collection<E> {2 public boolean remove(Object o);3 public void removeAll(Collection<?> c);4 }
Why? The answer is also because of backward compatibility. The X. Remove (o) interface indicates that "If O is contained in X, delete it; otherwise, nothing will be done ." If X is a generic set, O is not necessarily compatible with X's type parameters. If removeall () is generalized to be called (collection <? Extends E>), so before generalization, legal code sequences become invalid, for example:
1 // a collection of Integers2 Collection c = new HashSet();3 // a collection of Objects4 Collection r = new HashSet();5 c.removeAll(r);
If the preceding snippets are generalized in an intuitive way (set C to collection <integer> and R to collection <Object>), if the removeall () signature requires its parameter to be collection <? Extends E> instead of No-op, the above Code cannot be compiled. One of the main objectives of a generic class library is not to break or change the semantics of existing code. Therefore, you must define remove () with a type constraint that is weaker than the type constraint used to redesign the generic from the beginning (), removeall (), retainall (), and containsall ().
Classes designed before generics may impede the "obvious" generic method. In this case, it is necessary to make a compromise like the previous example. However, if a new generic class is designed from the beginning, it makes sense to understand what is backward compatible in the Java class library, this avoids improper imitation.
Implementation of Erasure
Because generics are basically implemented in Java compilers rather than runtime libraries, when bytecode is generated, almost all information about generic types is erased. In other words, the code generated by the compiler is basically the same as the code that you manually write without generics and checks program type security for forced type conversion. Unlike C ++, list <integer> and list <string> are the same class (although they are of different types, they are all list <?> This is a more important difference in JDK 5.0 compared with previous versions ).
Erasure means that a class cannot implement both comparable <string> and comparable <number> at the same time, because both of them are in the same interface and specify the same compareto () method. It seems wise to declare the decimalstring class to compare it with the string and number, but for the Java compiler, this is equivalent to two declarations on the same method:
1 public class DecimalString implements Comparable<Number>, Comparable<String>2 { ... } // nope
Another consequence of erasure is that it makes no sense to use forced type conversion or instanceof for generic type parameters. The following code does not improve the type security of the code at all:
1 public <T> T naiveCast(T t, Object o) { return (T) o; }
The compiler sends only one type without checking the conversion warning because it does not know whether the conversion is safe. The naivecast () method does not actually perform any conversion at all. t is directly replaced with an object. As expected, the passed object is forcibly converted to an object.
Erasure is also the cause of the preceding constructor problem. That is, you cannot create generic objects because the compiler does not know what constructor to call. If a generic class needs to construct an object of the specified type using the generic type parameter, the constructor should accept the class text (FOO. class) and save them to create instances through reflection.
Conclusion
Generics are a major step towards type security in Java, but the design of generic facilities and the generalization of class libraries are not without compromise. Extended virtual machine instruction sets to support generics are considered unacceptable, as this will cause insurmountable obstacles for Java vendors to upgrade their JVM. Therefore, the erasure method that can be fully implemented in the compiler is adopted. Similarly, in generic Java class libraries, maintaining backward compatibility sets many limitations for the class library's generalization methods, resulting in some messy and frustrating structures (such as array. newinstance ()). This is not a problem of generics, but related to language evolution and compatibility. However, this also makes generic learning and application more confusing and difficult.