Home  >  Article  >  Java  >  A closer look at generics in Java

A closer look at generics in Java

零下一度
零下一度Original
2017-07-18 09:47:091482browse

         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. Listbd43222e33876353aff11e13a7dc75f6 and Listf7e83be87db5cd2d9a8a0b8117b38cd4 are two different types, which are generated during the system runtime. Having its own virtual method table and type data, this implementation is called type inflation, and the generics implemented based on this method are called real generics.

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, ArrayListbd43222e33876353aff11e13a7dc75f6 and ArrayListf7e83be87db5cd2d9a8a0b8117b38cd4 are the same class. Therefore, generic technology is actually a syntactic sugar of the Java language. The generic implementation method in the Java language is called type erasure, and the generics implemented based on this method are called pseudo-generics. (Type erasure will be studied later)

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 Listf7e83be87db5cd2d9a8a0b8117b38cd4, it is directly limited that the list collection can only contain elements of String type.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn