Definition of generics: Generics are a new feature of JDK 1.5, and its essence is the application of parameterized types (Parameterized Type) , that is to say, the data type being operated is specified as a parameter, and the specific type is specified when used. This parameter type can be used in the creation of classes, interfaces and methods, called generic classes, generic interfaces and generic methods respectively.
The idea of generics began to take root as early as in the templates of the C++ language. When the Java language was in a version where generics had not yet appeared, Object could only be used as the parent class of all types. Type generalization can be achieved by combining the two features of type coercion. For example, in the access of hash tables, before JDK 1.5, the get() method of HashMap was used, and the return value was an Object object. Since all types in the Java language inherit from java.lang.Object, the Object can be transformed into any object. It’s possible in Chengdu. But because there are infinite possibilities, only the programmer and the virtual machine at runtime know what type of object this Object is. During compilation, the compiler cannot check whether the forced transformation of this Object is successful. If the programmer is solely relied on to ensure the correctness of this operation, many risks of ClassCastException will be transferred to the program runtime.
The way of using generic technology in C # and Java seems to be the same, but there are fundamental differences in implementation. In C #, generics are used both in the program source code and in the compiled IL (Intermediate Language) , intermediate language, at this time generics are a placeholder) or in the CLR at runtime. List
Generics in the Java language are different. They only exist in the program source code. In the compiled bytecode file, they have been replaced by the original raw type (Raw Type, also known as Naked type), and the cast code is inserted in the corresponding place, so for the Java language at runtime, ArrayList
The program code written using the generic mechanism is more secure and safer than the code that messily uses Object variables and then performs forced type conversion. readability. Generics are especially useful for collection classes.
1. Why use generics
Here we look at a piece of code;
List list = new ArrayList(); list.add("CSDN_SEU_Cavin"); list.add(100); for (int i = 0; i < list.size(); i++) { String name = (String) list.get(i); //取出Integer时,运行时出现异常 System.out.println("name:" + name); }
This example uses the list type A string type value and an Integer type value are added to the collection. (This is legal because the default type of list is Object). In the subsequent loop, due to forgetting to add an Integer type value to the list before or for other reasons, a java.lang.ClassCastException exception will occur at runtime. To solve this problem, generics came into being.
2. The use of generics
Generics allow programmers to use type abstractions, usually used in collections.
List<String> list = new ArrayList<String>();
Written like this, the above loop value acquisition method will not report an error, and there is no need to perform type conversion. Through List
3. Generics are only valid during compilation
We also need to understand when using generics What happens when generics are compiled, so here, we need to pay special attention to: generics are only valid when the code is compiled into a class file
AyyayList<String> a = new ArrayList<String>(); ArrayList b = new ArrayList(); Class c1 = a.getClass(); Class c2 = b.getClass(); System.out.println(a == b);
The output of the above program is true. This is because all reflection operations are performed at runtime. Since it is true, it proves that after compilation, the program will take de-genericization measures.
In other words, generics in Java are only valid during the compilation phase. During the compilation process, after the generic results are correctly verified, the relevant information of the generics will be erased, and type checking and type conversion methods will be added at the boundaries of the object's entry and exit methods. In other words, The successfully compiled class file does not contain any generic information. Generic information does not enter the runtime phase.
The following code explains very well that generics are only valid during compilation through Java’s reflection mechanism
ArrayList<String> a = new ArrayList<String>(); a.add("CSDN_SEU_Cavin"); Class c = a.getClass(); try{ Method method = c.getMethod("add",Object.class); method.invoke(a,100); System.out.println(a); //[CSDN_SEU_Cavin, }catch(Exception e){ e.printStackTrace();
4. Generics Classes and generic methods
public static class FX<T> { private T ob; // 定义泛型成员变量 public FX(T ob) { this.ob = ob; } public T getOb() { return ob; } public void showTyep() { System.out.println("T的实际类型是: " + ob.getClass().getName()); } } public static void main(String[] args) { FX<Integer> intOb = new FX<Integer>(100); intOb.showTyep(); System.out.println("value= " + intOb.getOb()); //java.lang.Integer System.out.println("----------------------------------"); FX<String> strOb = new FX<String>("CSDN_SEU_Calvin"); strOb.showTyep(); System.out.println("value= " + strOb.getOb()); //value= 100 }
5. Advantages of generics
(1) Type safety.
By knowing the type restrictions of variables defined using generics, the compiler can more effectively improve the type safety of Java programs.
(2) Eliminate forced type conversion.
Eliminate many casts in source code. This makes the code more readable and reduces the chance of errors. All casts are automatic and implicit.
(3) Improve performance
The above is the detailed content of A closer look at generics in Java. For more information, please follow other related articles on the PHP Chinese website!