[Simple Java] Java type erasure mechanism, simplejava
Java generics are a feature introduced by JDK 5. They allow us to use parameter types when defining classes and interfaces. generics are widely used in the collection framework. Type erasure is the most confusing part of generics. This article will illustrate what type erasure is and how to use it.
A common error
package simplejava;import java.util.ArrayList;public class Q29 { public static void main(String[] args) { ArrayList<String> al = new ArrayList<String>(); al.add("a"); al.add("b"); accept(al); } public static void accept(ArrayList<Object> al) { for (Object o : al) System.out.println(o); }}
The above code looks okay, Because String is a subclass of the Object. However, this does not work, compilation does not pass, and the following error is prompted:
The method accept (ArrayList <Object>) in the type Q29 is not applicable for the arguments (ArrayList <String>)
List <Object> and List <String>
The reason is that the data type is erased. Remember: The generic mechanism of Java is implemented at the compilation level. The bytecode generated by the compiler does not contain generic type information during runtime.
After compilation, List <Object> and List <String> are changed to List. The Object and String types are invisible to JVM. During the compilation phase, the compiler finds that they are inconsistent and therefore provides a compilation error.
Wildcard and bounded wildcard
List <? > Indicates that the List can contain any type of elements.
public static void main(String args[]) { ArrayList<Object> al = new ArrayList<Object>(); al.add("abc"); test(al); } public static void test(ArrayList<?> al) { for (Object e : al) {// no matter what type, it will be Object System.out.println(e); // in this method, because we don’t know what type ? is, we can not // add anything to al. } }
Always remember that generics are a compilation concept. In this example, since we do not know ?, We cannot add any elements to the al set. If you want to add a wildcard, you can use the wildcard.
List< Object > - List can contain Object or it’s subtypeList< ? extends Number > - List can contain Number or its subtypes.List< ? super Number > - List can contain Number or its supertypes.
Comparison with Arrays
Now we know that ArrayList <String> is not a child type of ArrayList <Object>. However, you need to know that if two generic types have the same parameters, their Inheritance relationships are based on their types. For example, ArrayList <String> is a child type of Collecton <String>.
However, arrays are different. They know the type of each element during runtime and force its elements to be of this type. This is called reification. For example, Object [] objArray is a super type of String [] strArr. If you try to add a String object to the array that stores the integer type, an ArrayStoreException exception is returned during running.
Http://www.programcreek.com/2011/12/java-type-erasure-mechanism-example/.