1. What is Generics?
Generics allow for parameterised types — for example, an instance of the Vector class can be declared to be a vector of strings (written Vector<String>) — and hence allow the compiler to enforce type safety. To avoid major changes to the Java run-time environment, generics are implemented using a technique called type erasure. This is equivalent to removing the additional type information and adding casts where required.
2. Type parameter
List<Object> list
3. Type erasure
Java Generics implementation realized based on compiler layer, there is no generics type parameter info. in java byte code. Type parameter in generics is removed when java class compile, this is called type erasure.
For example, List<Object> and List<String> are compiled to List. Type parameter is not visible for JVM. This mechanism is useful to find potential run time error when compile.
There are many characteristics related to type erasure:
- There is no class object for genericss. For example, no List<String>.class or List<Integer>.class.
- Generics class instances share all the static variable. For MyClass<T> class, use MyClass.myStaticVar to get the static variable.
- Generics can not be used in Java catch. For exceptions are handled when code run.
The following block of Java code illustrates a problem that exists when not using generics. First, it declares an ArrayList of type Object. Then, it adds a String to the ArrayList. Finally, it attempts to retrieve the added String and cast it to an Integer.
List v = new ArrayList();
v.add("test");
Integer i =(Integer)v.get(0); // Run time error
Although the code compiles without error, it throws a runtime exception(java.lang.ClassCastException) when executing the third line of code. This type of problem can be avoided by using generics and is the primary motivation for using generics.
Using generics, the above code fragment can be rewritten as follows:
List<String> v = new ArrayList<String>();
v.add("test");
Integer i = v.get(0);// (type error) Compile time error
The type parameter String within the angle brackets declares the ArrayList to be constituted of String(a descendant of the ArrayList's generic Object constituents). With generics, it is no longer necessary to cast the third line to any particular type, because the result of v.get(0) is defined as String by the code generated by the compiler.